Mysqli prepare statement breaks image insert into database - php

I have a sql statement that worked fine until I attempted to change it to a sql prepared statement.
Here is the old insert:
$sql = "INSERT INTO items (seller, post_date, expiration_date, image, description, name, category, startBid, buyPrice, minPrice, sold) VALUES ('$id_user', NOW(), '$postDate', '$image', '$description', '$itemName', 0, '$startBid', '$buyNow', '$reservation', 0)";
$db->send_sql($sql);
And I attempt to make it prepared here:
$stmt = $mysqli->prepare("INSERT INTO items (seller, post_date, expiration_date, image, description, name, category, startBid, buyPrice, minPrice, sold) VALUES (?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, 0)";
$stmt->bind_param("isbssiddd", $id_user, $postDate, $image, $description, $itemName, $itemCategory, $startBid, $buyNow, $reservation);
$stmt->execute();
$stmt->close();
Both statements execute but they result in different image values in the database. The image value of the first statement is what I expected and can retrieved/shown. The image put in with the prepared statement shows stuff put in the database but does not show up as a valid image. The image field is a longblob. Where am I going wrong? Thanks!

Figured out the issue. This is how I was getting my $image:
if (!empty($_FILES['inputPic']['tmp_name']))
{
if ($_FILES['inputPic']['type'] == "image/jpeg" || $_FILES['inputPic']['type'] == "image/jpg" || $_FILES['inputPic']['type'] == "image/png")
{
if ($content = file_get_contents($_FILES['inputPic']['tmp_name']))
{
$image = addslashes($content);
}
}
}
I needed the addslashes function in the old mysql statement but not when it is prepared now. Making it $image = file_get_contents($_FILES['inputPic']['tmp_name']) resolved the issue

Related

Can a prepared statement hold multiple queries in php

I am trying to protect my queries from SQL injections, recently. I have started turning the strings I used to make the queries into statements, however, some of the strings I made need to make multiple queries simultaneously, because one insert's id will be added to the next one as a foreign key, which I'll get by using the LAST_INSERT_ID(), and I need them to be executed one after another because of it.
Can a statement hold multiple queries simultaneously and be executed at once?
Here's what the code was before, by the by.
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES ('{$firstName}', '{$lastName}', '{$phone}', '{$cpf}');";
$sql .= "SELECT LAST_INSERT_ID() INTO #mysql_variable_here;";
$sql .= "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES ('{$email}','{$password}', 1, #mysql_variable_here, '{$created}', {$role}" . $restaurantValue . " );";
$sql .= "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES ('{$number}', '{$street}', '{$city}', '{$stateCode}', '{$zip}', '{$district}', 'BR', '{$created}', #mysql_variable_here);";
$result = $conn->multi_query($sql);```
You can't execute multiple statements in a prepared query:
SQL syntax for prepared statements does not support multi-statements
(that is, multiple statements within a single string separated by ;
characters)
so you will need to prepare and execute each of the queries separately, using mysqli_stmt::insert_id to get the appropriate id value for the second and third queries:
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $firstName, $lastName, $phone, $cpf);
$stmt->execute();
$insert_id = $stmt->insert_id;
$stmt->close();
$sql = "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssiisss', $email, $password, 1, $insert_id, $created, $role, $restaurantValue);
$stmt->execute();
$stmt->close();
$sql = "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$country = 'BR';
$stmt->bind_param('sssssssi', $number, $street, $city, $stateCode, $zip, $district, $country, $created, $insert_id);
$stmt->execute();
$stmt->close();
Note I'm not 100% certain what you're trying to achieve with role_id" . $restaurantInsert . ", you might need to edit the second query appropriately to use that.

SQL Prepared statement not inserting my values

I have this prepared statement and it isn't inserting into the table at all. The connection to my database is working. I am still new to this so I am unsure on what is wrong. The spelling of my table is correct also. My network tab on inspect element doesn't show any errors as if it did insert the data but the table doesn't update with said data.
$stmt = $conn->prepare("INSERT INTO usersreports (DateOfReport,Username,ReportedPostId,ReportedUser,ReportedUserId,ReportedReason,ReportedTopic,Resolved,Response,ActionTaken) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $DateOfReport,$YourUsername,$UsersPostId,$ReportedUsername,$ReportedUserId,$ReportReason,$ReportTopic,$Resolved,$Response,$ActionTaken);
if ( $stmt === false ) {
echo $conn->error;
exit;
}
$stmt->execute();
$stmt->close();
$conn->close();

Inserting an Image and Date into Db with Prepared Statements

I have the following query that I'm trying to convert to a prepared statement:
$NewPostQ = mysqli_query($con, "INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES('$DateTime', '$Title', '$Category', '$Admin', '$Image', '$Post')");
Here is what I have:
$NewPostQ = mysqli_prepare($con, "INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES(?, ?, ?, ?, ?, ?)");
$NewPostQ->bind_param("isssbs", $DateTime, $Title, $Category, $Admin, $Image, $Post);
$NewPostQ->execute();
move_uploaded_file($_FILES["Image"]["tmp_name"], $Target);
Everything is going into the DB except the image and the datetime. I have $Datetime as follows:
$CurrentTime = time();
$DateTime = strftime("%b-%d-%Y %H: %M: %S", $CurrentTime);
It's going into a varchar(50) in dB. Image is as follows:
$Image = $_FILES["Image"]["name"];
$Target = "../assets/upload/".basename($_FILES["Image"]["name"]);
This is going into varchar(200) in dB. My understanding was that dates were characterized as integers and images as blobs in bind_param so I set them as i and b ("isssbs"). Does anyone know why this wouldn't be working? In datetime I get a zero and for image it's just empty.

Catch Duplicate entry with prepared SQL statement

I want to handle the "Duplicate entry" error with a prepared MySQL statement.
I have thoses lines
$result = $db->prepare("INSERT INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
$result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date));
And want to execute some code if there is not any error. And display a pop-up and make the prog die if there is an error.
I already tried
if($result === false)//Catch error
{}
else //It worked
{}
But it did not worked
You can use INSERT IGNORE and then check how many rows were affected using PDOStatement::rowCount
Concept should be along the lines of:
$result = $db->prepare("INSERT IGNORE INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
if ($result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date))) {
if ($result->rowCount() == 0) {
// You had a duplicate record.
} else {
// all good.
}
}

Insert into table with prepared statement

I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.
I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.
Here's my prepared statement:
if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
$newBlog->execute();
$newBlog->close();
}
It's just not inserting the values into my table.
You are generating SQL containing strings that are not quoted or escaped.
Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.
$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
Since you are aware about prepared statement:
$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
since you are using auto increment field you need to specify column name and then values
try this code
$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();

Categories