I am new to pdo and do not get why the following insert query does not work. If I remove the line that executes the query, there will be of course no insertion, but there will be no error. If I leave that line, the script is not executed. Of course I checked and rechecked the table name and field name. Hope someone can hep me understand. Note that before executing the query, the ber_mBacth_date field of my table is set to NULL. Cheers. Marc
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_password = 'user';
$db_database = 'myconsole';
$mBatchDate = date('Y-m-d H:i:s');
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
$connexion = NULL;
?>
Can you try instead of:
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
do:
$statement = $connexion->prepare("UPDATE batcherrors SET ber_mBatch_date = :mBatchDate");
$statement->bindValue(':mBatchDate', $mBatchDate, PDO::PARAM_STR);
$statement->execute();
Binding is recommended way to set parameters values (over concatenation).
Related
Trying to insert values into MS Access DB based on values entered into a powershell form with a WHERE clause. I'm receiving a simple error but struggling to resolve ("Missing Semicolon (;) at end of SQL Statement")
Here is my base code;
$query = "INSERT INTO SignIns ([DateTimeOUT], [SignedOut]) VALUES ('$($info.F1)','$($info.F2)') FROM $Info WHERE SignIns.Surname = '$($Info.F3)'"
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query
$result = $cmd.ExecuteNonQuery()
$conn.Close()
I've amended to add a semicolon in all places I thought could resolve, but no luck, still returns the same error (Missing Semi Colon at end of SQL statement);
$query = "INSERT INTO SignIns ([DateTimeOUT], [SignedOut]) VALUES ('$($info.F1)','$($info.F2)') FROM $Info WHERE SignIns.Surname = '$($Info.F3);';";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$conn.Close()
(for reference, I've added a semi-colon at the end of my WHERE clause, at the end of the $Query variable and tried to append onto the end of $query when executing in the $cmd.commandtext variable, and also on the end of the $result variable.
I expect the statement to execute as normal and update with the given values. Testing within Access DB itself is difficult as I am unable to reference my PS form from within the DB. Any help greatly appreciated,
Thanks.
Update: Ameding query to UPDATE now lets me 'insert' values with WHERE statement following a simple logic.
$conn.Open()
$query = "UPDATE SignIns SET DateTimeOUT = '$($info.F1)' WHERE SignIns.Surname = '$($Info.F3)'";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$query = "UPDATE SignIns SET SignedOut = '$($info.F2)' WHERE SignIns.Surname = '$($Info.F3)'";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$conn.Close()
It is not a method I'm normally use to when inputting new values into a table, but same result so.. I don't think there's any implications. It probably takes the update as 'Update from NULL to VALUE' as opposed to INSERT FROM source to DESINTATION (where)
I am trying to fetch the single row using the pdo statement, but i am getting the error like ..
Fatal error: call to undefined method fetch()
$sql = new Sql( $this->adapter );
$select = $sql->select();
$select->from('users');
$where = new Where();
$where->equalTo('user_id',$userId);
$select->where($where);
//echo $select->getSqlString($this->adapter->getPlatform());
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$row = $statement->fetch();
//getting the result set for the below, but not the above statement fetch
$rows = array_values(iterator_to_array($result));
There's no "fetch" method in the statement object. If you want to get a single row then get the current entry of the result iterator, like so:
$row = $result->current();
I'm brand new to PDO statements, and this is my very first attempt.
I'm not completely sure if the code I have produced is achieving anything?
Am I protected from coding-genius-hackers?
<?php
$host = "localhost";
$db = "test";
$user = "root";
$pass = "admin";
$who = '65';
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT
tbl_tracking.id as trackID,
tbl_tracking.from_user as trackFROM,
tbl_tracking.viewed as trackVIEWED,
tbl_tracking.date as trackDATE,
tbl_users.id as usrID,
tbl_users.name as usrNAME,
tbl_photos.profile as photosPROFILE,
tbl_photos.photo_link as photoLINK,
tbl_photos.default_photo as photoDEFAULT
FROM tbl_tracking
LEFT JOIN tbl_users ON tbl_tracking.from_user = tbl_users.id
LEFT JOIN tbl_photos ON tbl_photos.profile = tbl_users.id
WHERE tbl_tracking.viewed = '$who' AND tbl_photos.default_photo IS NULL OR tbl_photos.default_photo = '1'
GROUP BY tbl_tracking.from_user
ORDER BY tbl_tracking.id DESC
LIMIT 9
";
$q = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo '<img src="../assets/uploads/thumbnail_' . $r['photoLINK'] . '" class="suggestUser" />';
}
?>
To be protected against sql injection, you must use PDO's new of verifying values: binding parameters. This needs that your prepare statements instead of running them directly:
$q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
Change your where clause:
WHERE tbl_tracking.viewed = :who AND tbl_photos.default_photo IS NULL OR tbl_photos.default_photo = '1'
then bind the value to your statement and execute it:
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->execute();
or you can execute it directly with an array of values:
$q->execute(array(':who' => $who));
otherwise, I'm not very sure what your code should be doing, so I can't really tell if it will, but if your sql worked before using PDO, it should work now too.
For your code to be prone to sql injection, one of the values in your query must have a way to come from user-input, and it must be passed as-is to PDO's prepare(). Since we use a parameter :who instead of $who, there's no way your sql will be prepared with dangerous values.
I'm trying to perform a search in one of my tables based on a given criteria like so:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$currencies = User::model()->findAll($criteria, array(':currency' => $id,));
I get a CDbException:
CDbCommand failed to execute the SQL statement:
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound.
The SQL statement executed was:
SELECT * FROM `user` `t`
WHERE usr_currency=:currency
Where as, this works:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$criteria->params = array(':currency' => $id,);
$comments = User::model()->findAll($criteria);
What is wrong with the first code fragment?
From CActiveRecord::find()
This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
I have a select statement see below. Using PDO how would I recreate this same Select statement, as I want to grab two values from it and combine them into the $geomstring. I can figure out the combine, but not the first 3 lines.
$sql1 = "SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id='$_POST[gridref_id]'";
$result1 = pg_query($sql1);
$row1 = pg_fetch_array($result1);
$geomstring = $row1['easting_value']. $_POST['grid_eastings']." ".$row1['northing_value'].$_POST['grid_northings'];
*php website for prepared statements says *
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
I have something similar working for populating a dropdown that partly uses this
$stmt = $conn->prepare("SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id=$gridref_id");
$stmt->setFetchMode(PDO::FETCH_OBJ);
Found it on php.net, I was googling the wrong stuff:
$stmt4 = $conn->prepare("SELECT easting_value, northing_value from gridreference_tbl WHERE gridref_id = 4");
$stmt4->execute();
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $stmt4->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");