i'm trying to create a multiple photo uploading script in php. All seems to be working fine except the update query. tried updating it manually in phpmyadmin and the problem of not updating persists don't know what to do can any experts help me solve this problem.
here is the update query:
try {
$sql1="update photos
set
filename='{$db_file_name}',
upload_date=now() where user='{$_SESSION['id']}' ";
$st1=$conn->prepare($sql1);
$st1->execute();
}
catch (Exception $exc) {
echo $exc->getMessage();
}
First of all, I would verify again whether all the variables you are using are correct (photos, filename, etc.). i.e. compare them letter by letter with your table. If that looks alright, a little more information wouldn't be bad. Are you getting any errors? If so, what are they saying? What else have you tried so far?
Moreover, I would suggest making your code a little easier to read like so:
/* create a prepared statement */
if ($st1 = $conn->prepare("UPDATE `photos` SET `filename` = ?, `upload_date` = ? WHERE `user` = ?")) {
/* bind parameters (ssi = string, string, integer)*/
$st1->bind_param("ssi", $db_file_name, now(), $_SESSION['id']);
/* execute query */
$st1->execute();
/* close statement */
$st1->close();
}
user is a keyword, better use backticks around it. See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
try {
$sql = "UPDATE `photos`
SET `filename` = :filename,
`upload_date` = NOW()
WHERE `user` = :sess_id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":sess_id", $_SESSION['id']);
$stmt->bindValue(":filename", $db_file_name);
$stmt->execute();
} catch (....) {
....
}
Perhaps better still, don't use keywords as column names, try userId.
Related
I am using PHP to do some database projects for school in a self pace class, so I don't know much of the syntax. I am trying to change a row of by database based on the ID given.
Heres some pseudocode of what I want to accomplish:
if(databaseRowWithThis$id name == x)
UPDATE database SET name = '$name' WHERE id='$id';
If this is confusing, please tell me and I'll try to clear it up.
Thanks in advance.
PHP with Syntax
$conn = mysqli_connect($server,$login,$pw,$database); // connection info
$sql = "UPDATE yourtablename SET name= ? WHERE id=?"; // placeholders for parameters
$stmt = $conn->prepare($sql); // prepare the query
if($stmt){
$stmt->bind_param("is",$id,$name); // bind the parameters to the ?, i for integers, s for string, must be in exact order as the query
$stmt->execute(); // execute
$stmt->close(); // close statement
}
$conn->close(); // close the connection
I am busy trying to execute a set of statements that involve the use of a temporary table.
My goal is to create the temporary table, insert values to it and then do a like comparison of the temporary tables contents to another table.
These statements are working perfectly in phpmyadmin when executed from RAW SQL, but I'm assuming that the table is not available when I try to insert the data.
Below is the code for my php function + mysqli execution:
function SearchArticles($Tags){
global $DBConn, $StatusCode;
$count = 0;
$tagCount = count($Tags);
$selectText = "";
$result_array = array();
$article_array = array();
foreach($Tags as $tag){
if($count == 0){
$selectText .= "('%".$tag."%')";
}else {
$selectText .= ", ('%".$tag."%')";
}
$count++;
}
$query = "CREATE TEMPORARY TABLE tags (tag VARCHAR(20));";
$stmt = $DBConn->prepare($query);
if($stmt->execute()){
$query2 = "INSERT INTO tags VALUES ?;";
$stmt = $DBConn->prepare($query2);
$stmt->bind_param("s", $selectText);
if($stmt->execute()){
$query3 = "SELECT DISTINCT art.ArticleID FROM article as art JOIN tags as t ON (art.Tags LIKE t.tag);";
$stmt = $DBConn->prepare($query3);
if($stmt->execute()){
$stmt->store_result();
$stmt->bind_result($ArticleID);
if($stmt->num_rows() > 0){
while($stmt->fetch()){
array_push($article_array, array("ArticleID"=>$ArticelID));
}
array_push($result_array, array("Response"=>$article_array));
}else{
array_push($result_array, array("Response"=>$StatusCode->Empty));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
$stmt->close();
return json_encode($result_array);
}
The first statement executes perfectly, however the second statement gives me the error of:
PHP Fatal error: Call to a member function bind_param() on a non-object
If this is an error to do with the Temp table not existing, how do i preserve this table long enough to run the rest of the statements?
I have tried to use:
$stmt = $DBConn->multi_query(query);
with all the queries in one, but i need to insert data to one query and get data from the SELECT query.
Any help will be appreciated, thank you!
You have a simple syntax error use the brackets around the parameters like this
INSERT INTO tags VALUES (?)
This is not an issue with the temporary table. It should remain throughout the same connection (unless it resets with timeout, not sure about this part).
The error is that $stmt is a non-object. This means that your query was invalid (syntax error), so mysqli refused to create an instance of mysqli_stmt and returned a boolean instead.
Use var_dump($DBConn->error) to see if there are any errors.
Edit: I just noticed that your query $query2 is INSERT INTO tags VALUES ? (the ; is redundant anyway). If this becomes a string "text", this would become INSERT INTO tags VALUES "text". This is a SQL syntax error. You should wrap the ? with (), so it becomes INSERT INTO tags VALUES (?).
In conclusion, change this line:
$query2 = "INSERT INTO tags VALUES ?;";
to:
$query2 = "INSERT INTO tags VALUES (?);";
also note that you don't need the ; to terminate SQL statements passed into mysqli::prepare.
I have a really simple procedure I need to do, and no matter how much I debug or simplify, the record is not updating in the dbase. Assume everything is correct in terms of connection, etc. Pulling this from php and doing a MySQL call in PHPMyAdmin results in a correct record update on the table. I've tried using/not using quotes around adminId.
Any ideas?
$sampleString = "343r34c3cc43";
//Need to store the customer ID from sub system
$stmt2 = $mysqli->prepare("
UPDATE
admins
SET
chargebeeId = '?'
WHERE
adminId='22'
");
$stmt2->bind_param('s',
$mysqli->real_escape_string($sampleString)
);
$stmt2->execute();
For reference, adminId will be dynamic, with a bind_param 'i' in the application.
change this
chargebeeId = '?'
to
chargebeeId = ?
try this
$sampleString = "343r34c3cc43";
$sampleString = $mysqli->real_escape_string($sampleString) ;
$stmt2 = $mysqli->prepare("UPDATE admins
SET chargebeeId = ?
WHERE adminId='22' ");
$stmt2->bind_param('s', $sampleString);
$stmt2->execute();
I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()
I have the following table:
ID: bigint autoinc
NAME: varchar(255)
DESCRIPTION: text
ENTRYDATE: date
I am trying to insert a row into the table. It executes without error but nothing gets inserted in database.
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,?)";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$curdate = "CURDATE()";
$stmt->bind_param("sss", $name, $desc, $curdate);
$stmt->execute();
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e;
}
It runs fine and redirects to success page but nothing can be found inside the table. Why isn't it working?
What about replacing DESCTIPTION with DESCRIPTION inside the $query?
Edit
Just out of curiosity, I created a table called mytable and copy-pasted your code into a PHP script.
Here everything worked fine and rows got inserted, except that the binded parameter CURDATE() did not execute properly and the ENTRYDATE cell was assigned 0000-00-00.
Are you sure you are monitoring the same database and table your script is supposedly inserting to?
What happens when going with error_reporting(E_ALL); ?
Have you verified that the script actually completes the insertion?
The following appears to be working as expected:
error_reporting(E_ALL);
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES (?, ?, CURDATE())";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$stmt->bind_param("ss", $name, $desc);
$stmt->execute();
if ($conn->affected_rows < 1) {
throw new Exception('Nothing was inserted!');
}
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e->getMessage();
}
Are you sure there is no error? There seems to be a typo in your column name for example.
Note that PDO is extremely secretive about errors by default.
See How to squeeze error message out of PDO? on how to fix this.
Try preparing this query instead:
"INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,CUR_DATE())"
And check the results of $stmt->execute(). It would have given you a warning that "CUR_DATE()" (sic) is not a valid DATE.
You can check if a statement was correctly executed by checking the return value of execute() and querying the errorInfo() method:
if (!$stmt->execute()) {
throw new Exception($stmt->errorInfo(), stmt->errorCode());
}
Be aware that upon failure, execute() does not throw an exception automagically. You'll have to check for successful operation and failure for yourself.
Is it possible that autocommit is OFF?
If so then you have to commit your insert like so
/* commit transaction */
$conn->commit();
Regards