PDO -> if(table exist) - pdo

try {
$query = $pdo->query("SELECT 1 FROM `classes` LIMIT 1");
} catch (Exception $e) {
$query = $pdo->prepare("CREATE TABLE `classes`(
`ID_class` int(11) AUTO_INCREMENT,
`name` varchar(255),
PRIMARY KEY(`ID_class`))");
$query->execute();
}
Hello.
It doesn't catch, if the table doesn't exist.

This is not going to work because, according to the PHP documentation (php.net):
Return Values
PDO::query() returns a PDOStatement object, or FALSE on failure.
So you either need to test if $pdo->query("SELECT 1 FROM 'classes' LIMIT 1") returns false or an alternative like checking if a table exists without using 'select from' (stackoverflow.com).

It worked for me with the PDO ATT_ERRMODE set to ERRMODE_EXCEPTION.
$user = 'test';
$pass = 'test';
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8' ,
$user ,
$pass ,
$opt
);
try {
$query = $db->query("SELECT 1 FROM `classes` LIMIT 1");
} catch (Exception $e) {
$query = $db->prepare("CREATE TABLE `classes`(
`ID_class` int(11) AUTO_INCREMENT,
`name` varchar(255),
PRIMARY KEY(`ID_class`))");
$query->execute();
}

Related

How can I add to an existing value in sql table

How can i add a value to an existing value in SQL example a value 4 in a column how can i add 2 to it to make it 6 not to update to 2 but to add the previous value and the new value to together here is my class php file
<?php
class data
{
public $d_count;
public $id;
private $conn;
private $table_name;
public function __construct($db)
{
$this->conn = $db;
$this->table_name= "tbl_data";
}
public function updateCount()
{
// $query = "UPDATE tbl_data SET d_count = ?, date_updated = ? WHERE id = ?";
$query = "UPDATE tbl_data SET d_count '+1' = ?, date_updated = ? WHERE id = ?";
$obj = $this->conn->prepare($query);
$this->d_count = htmlspecialchars(strip_tags($this->d_count));
$this->date_updated = htmlspecialchars(strip_tags($this->date_updated));
$this->id = htmlspecialchars(strip_tags($this->id));
$obj->bind_param("sss", $this->d_count, $this->date_updated, $this->id);
if ($obj->execute()) {
return true;
}
return false;
}
}
The line I commented out is what i used to test the code and it works fine but now i need to add the old value + new value together here is the code am using to update the table
<?php
$data = new data($connection);
if($_SERVER['REQUEST_METHOD'] === "POST"){
$newDCount = json_decode(file_get_contents("php://input"));
if(!empty($newDCount->d_count))
$data->id= $newDCount->id;
$data->d_count = $newDCount->d_count;
$data->date_updated = date('Y-m-d H:i:s', time());
if($apiata->updateCount()){
http_response_code(200);
echo json_encode(array(
"status" => 200,
"message" => "Success"
));
}
else
{
http_response_code(200);
echo json_encode(array(
"status" => 500,
"message" => "Failed"
));
}
}
To update the d_count to add to the existing d_count value, the query should look like:
$sql = 'UPDATE catalog SET d_count = d_count + ?, date_updated = ? WHERE id = ?';
The other handling should be ok as-is.

IF SQL #ID EXISTS, DO NOT INPUT?

I made a Powershell script that inputs data from a Powershell O365 Health Module into a SQL Database by using a Foreach loop. The issue I am having now is that each time I run the script (every 30 minutes or something), it creates new lines into my database, and most of the time it's duplicates.
One of the values (#ID) is unique, so what I want to do is:
If #ID FROM table exist, DO Nothing. So it should then only skip that line in the Foreach statement and continue into the next one and continue writing the others into the table.
I am kinda new to SQL so I am a bit unsure how to do this.
Here's my script:
$o365user = 'user#company.com'
Import-Module O365ServiceCommunications
$Credential = Get-Credential $o365user
$Session = New-SCSession -Credential $Credential -locale en-US
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = 'Server=testcoresight;Database=O365Health;Integrated Security=True'
$SqlConnection.Open();
$sql = #'
INSERT INTO O365Events(
StartTime,
EndTime,
ID,
EventType,
Service,
Status
)
VALUES (
#StartTime,
#EndTime,
#ID,
#EventType,
#Service,
#Status
)
'#
$cmd = $SqlConnection.CreateCommand()
$cmd.CommandTimeout = 15
$cmd.CommandText = $sql
[void]$cmd.Parameters.Add('#StartTime',[string])
[void]$cmd.Parameters.Add('#EndTime',[string])
[void]$cmd.Parameters.Add('#ID',[string])
[void]$cmd.Parameters.Add('#EventType',[string])
[void]$cmd.Parameters.Add('#Service',[string])
[void]$cmd.Parameters.Add('#Status',[string])
#Gets O365 Health Status. Shows Incident types for the past 7 days and sends them to the SQL DB.
Get-SCEvent -SCSession $Session -EventTypes Incident -pastdays 7 |
ForEach-Object {
Try{
$cmd.Parameters['#StartTime'].Value = if($_.StartTime){$_.StartTime}else{''}
$cmd.Parameters['#EndTime'].Value = if ($_.EndTime) { $_.EndTime } else { '' }
$cmd.Parameters['#ID'].Value = if ($_.ID) { $_.ID } else { '' }
$cmd.Parameters['#EventType'].Value = if ($_.EventType) { $_.EventType } else { '' }
$cmd.Parameters['#Service'].Value = if ($_.AffectedServiceHealthStatus.ServiceName) { $_.AffectedServiceHealthStatus.ServiceName } else { '' }
$cmd.Parameters['#Status'].Value = if ($_.Status) { $_.Status } else { '' }
Write-Host ID Loaded: $_.ID -ForegroundColor green
if ($cmd.ExecuteNonQuery() -ne 1) {
Write-Host Insert failed: $_.ID
}
}
Catch{ Write-Host $_ }
}
$SqlConnection.Close()
What I believe I have to do is add something like:
IF #ID EXISTS FROM O365Events skip
INSERT INTO O365Events(
StartTime,
EndTime,
ID,
EventType,
Service,
Status
)
SELECT
#StartTime,
#EndTime,
#ID,
#EventType,
#Service,
#Status
WHERE NOT EXISTS (SELECT null FROM O365Events WHERE ID = #ID)
Or, really, you could just make the ID the promary key and handle the error that occurs when you try to insert a duplicate

Retrieving a int value from database

I am trying to get sender_id and receiver_id into my variables but it is giving me following error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
object given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line
36
Warning: mysql_fetch_row() expects parameter 1 to be resource, object
given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line 42 N
CODE:
<?php
$sender_id = 0;
$receiver_id = 0;
session_start();
if(isset($_SESSION['login_user'])) {
//header('location: chat.php');
}
else {
header('location: chatlogin.php');
}
if(isset($_REQUEST['sender']) AND isset($_REQUEST['msg']) AND isset($_REQUEST['time']) AND isset($_REQUEST['receiver']) ){
$msg = $_REQUEST['msg'];
$time = $_REQUEST['time'];
$sender = $_REQUEST['sender'];
$receiver = $_REQUEST['receiver'];
echo $sender;
echo $receiver;
echo $msg;
echo $time;
//echo $msg;
if ( empty($_REQUEST['msg']) ) {
}
else{
require_once 'dc_chat.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $mysqli -> query("SELECT id from users where username LIKE '{$sender}'");
$row = mysql_fetch_row($result);
$sender_id = $row[0];
$result = $mysqli -> query("SELECT id from users where username LIKE '{$receiver}'");
$row = mysql_fetch_row($result);
$receiver_id = $row[0];
//echo $receiver_id;
$sql = $mysqli -> query("INSERT INTO `messages` (`sender_id`, `receiver_id`, `msg`, 'chattime') VALUES ('{$sender_id}', '{$receiver_id}', '{$msg}' ,'{$time}')");
if(! $sql ) {
echo 'N';
}
else {
echo 'Y';
}
}
}
else{
echo "hello";
}
?>
I am getting $msg, $time, $sender, $receiver from a ajax and datatype is JSON
You are mixing mysql and mysqli functions. mysql_fetch_row should probably be mysqli_fetch_row.
Replace if (!$sql) with if ($mysqli->affected_rows == 0) to test for success on the INSERT statement.
If you suspect an error in your SQL statement use echo $mysqli->error; after your query line to put that on the screen.

Integrity constraint violation when ID does exist

After searching around, it seems like the problem is that the id doesn't exist in table 1 when inserting into table 2 BUT it does exist in my table! Actually this was working fine for few months until yesterday.
Error: Cannot add or update a child row: a foreign key constraint fails review CONSTRAINT reviews_ibfk_1 FOREIGN KEY (user_id) REFERENCES user(user_id))
public function actionAjaxComment($id) {
$prod_id= $id;
if(Yii::app()->request->isAjaxRequest) {
$model=new Review;
$this->performAjaxValidation($model);
$user_id = Yii::app()->user->user_id;
$criteria = new CDbCriteria;
$criteria->compare('target_product_id',$prod_id);
$criteria->compare('user_id',$user_id);
$record = $model->findAll($criteria);
$model->attributes=$_POST['Review'];
if(empty($record)) {
$date = Yii::app()->getDateFormatter()->formatDateTime(time(), 'long', 'short');
$model->user_id = $user_id;
$model->target_product_id = $prod_id;
$model->review_date = time();
$uname = ucwords(Yii::app()->user->username);
$img = User::model()->FindByPk($user_id)->image;
$img_url = Yii::app()->basePath."/images/user/".$img;
$img = Yii::app()->assetManager->publish($img_url);
$model->save();
echo CJSON::encode(
array('status'=>'success',
'star'=>$model->star,
'review'=>$model->review,
'user'=>$uname,
'uimg'=>$img,
'date'=>$date,
));
return $model->review;
} elseif(!empty($record)) {
echo CJSON::encode(
array('status'=>'dup'
));
} else
echo CJSON::encode(
array('status'=>'error'
));
Yii::app()->end();
}
}
Is your user_id a foreign key? If yes, the maybe the table which it points to doesn't have a row with the user id you are trying to assign it to

PHP PDO dynamically updating db table with multiple records to a specific user ID

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}
Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);