Inserting an Image and Date into Db with Prepared Statements - php

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.

Related

Mysqli bind parameters not working

I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

Two insert statements in php [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Hi guys how do I have two insert statements in the php codes to store the data into two different tables in the database?
$order = "INSERT INTO NewCase(CaseID, StaffName, Category, PriorityLevel, Status, Date, Summary, ResidentID)
VALUES (NULL, '$staffname', '$category', '$prioritylevel', '$status', '$checkdate', '$summary', NULL)";
$order .= "INSERT INTO NewResident(ResidentID, NRIC, ResidentName, Telephone, Email, Gender, Street1, Street2, PostalCode)
VALUES (NULL, '$nric', '$residentname', '$telephone', NULL, NULL, '$street1', '$street2', '$postalcode')";
$retval = mysqli_multi_query($link, $order);
You should be using mysqli prepared statements and nothing else.
$sql = "INSERT INTO NewCase VALUES (NULL, ?, ?, ?, ?, ?, ?, NULL)";
$stmt = $link->prepare($sql);
$stmt->bind_param("ssssss",$staffname, $category, $prioritylevel, $status, $checkdate, $summary);
$stmt->execute();
$sql = "INSERT INTO NewResident VALUES (NULL, ?,?,?, NULL, NULL, ?,?,?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("ssssss",$nric, $residentname, $telephone, $street1, $street2, $postalcode);
$stmt->execute();
Take a look into transactions may be?
http://php.net/manual/en/mysqli.begin-transaction.php
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
mysqli_query($link, $order1);
mysqli_query($link, $order2);
mysqli_commit($link);
mysqli_close($link);
Also if transaction fail you can always rollback
Also I suggest you use more Object Oriented approach:
$mysqli = new mysqli("localhost", "user", "password", "world");
$mysqli->query();
$mysqli->query();
$mysqli->close();

Best Way to Insert a unix timestamp using PHP into a mySQL integer field (INT)?

I have a table and theDate field is structured as INT (32) .
Writing PHP scripts I would like to use mySQL PDO to insert the unix timestamp as an integer into theDate INT table field. What is the best way to do this? And what is the most efficient size for my theDate field? 8, 16, 32?
code:
$theDate = now(); // this returns a 0 in theDate mySQL field
$stmt = $db->prepare("INSERT INTO countries(name, capital, language, theDate) VALUES (:country, :capital, :language, :theDate)");
$stmt->bindParam(':country', $country, PDO::PARAM_STR, 100);
$stmt->bindParam(':capital', $capital, PDO::PARAM_STR, 100);
$stmt->bindParam(':language', $language, PDO::PARAM_STR, 100);
$stmt->bindParam(':theDate', $theDate );
if($stmt->execute()) {
echo '1 row has been inserted';
}
I have googled this and searched this site.. can't find a good answer
thanks
The best way to store a datetime information in mysql is to use a datetime field. For which you can use the very now() function you were trying. But of course you have to call it in SQL, not PHP:
$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, now())";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language]);
if you insist on using unreliable and outdated unix_timestamp, you have to use unix_timestamp() SQL function instead of now(). The code would be the same as above, save for the function name.
If you want to send an int value to a database via PDO - just send it:
$theDate = time();
$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language,$theDate]);

Mysqli prepare statement breaks image insert into database

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

PHP getdate() not returning the same day/month when used at two separate places in my code

I have a function that calls another function to write some values into an MSSQL database. It takes the string request as first argument and an array containing the values to enter in the query (where there are ? in the query) if these are contained in a variable and cannot be explicitly written in the query. Here is the function in question:
public function dbInsert(){
$curr_date = date('Y-m-d H:i:s');
$this->db->query("INSERT INTO DAI_REQ.META_REQUEST ".
"(DATE_RECU, DATE_TERMINEE, USER_ID, STATUS) ".
"VALUES(?, '', ?, 'R');", array($curr_date, $this->userId));
$mr_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.META_REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$mr_result = $mr_select->result_array();
$mr_id = $mr_result[0]['ID'];
$sim = 'N/A';
if(isset($this->recurrenceType))
$sim = 'Recurrent';
$this->db->query("INSERT INTO DAI_REQ.REQUEST ".
"(USER_ID, ASSIGNED_DATE, REQUEST_END_DATE, MODEL, EXPERIMENT, VARIABLE, START_DATE, END_DATE, ".
"LON_FROM, LAT_FROM, LON_TO, LAT_TO, RESOLUTION, FORMAT, SIMULATION, STATUS, ".
"CANCELLED_YN, PROJECT, MR_ID, URL_ORIGIN, DATE_EMAIL) ".
"VALUES(?, ?, '', ?, 'N/A', 'N/A', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'R', 0, 'N/A', ?, ?, ?);",
array($this->userId, $curr_date, $this->model, $this->startDate, $this->endDate,
$this->lonFrom, $this->latFrom, $this->lonTo, $this->latTo,
$this->resolution, $this->format, $sim, $mr_id, $this->url_origin, $this->date_email));
$r_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$r_result = $r_select->result_array();
$this->id = $r_result[0]['ID'];
}
As you can see, I call the query function two times, and within those two queries I use the variable $curr_date that contains the date of today. Unfortunately, when I go look into the database with sql-server after running this code, the date I see in the DAI_REQ.META_REQUEST table is not the same as the date in the DAI_REQ.REQUEST table. The latter contains the good date while the former contains a random date (though the date is similar each day I try it). For exemple, the latter would 2014-06-30 14:08:40.427 and the former would be 2014-02-19 00:00:00.000
I also have to mention that we have two servers (so two databases also), one for development and one for public deployment. The problem I am describing occurs on the public deployment server, but not on the development server.
I have also tried to remove the use of the $curr_date variable by directly calling the getdate() function inside the query function as follows:
$this->db->query("INSERT INTO DAI_REQ.META_REQUEST ".
"(DATE_RECU, DATE_TERMINEE, USER_ID, STATUS) ".
"VALUES(GETDATE(), '', ?, 'R');", array($this->userId));
...
$this->db->query("INSERT INTO DAI_REQ.REQUEST ".
"(USER_ID, ASSIGNED_DATE, REQUEST_END_DATE, MODEL, EXPERIMENT, VARIABLE, START_DATE, END_DATE, ".
"LON_FROM, LAT_FROM, LON_TO, LAT_TO, RESOLUTION, FORMAT, SIMULATION, STATUS, ".
"CANCELLED_YN, PROJECT, MR_ID, URL_ORIGIN, DATE_EMAIL) ".
"VALUES(?, GETDATE(), '', ?, 'N/A', 'N/A', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'R', 0, 'N/A', ?, ?, ?);",
array($this->userId, $this->model, $this->startDate, $this->endDate,
$this->lonFrom, $this->latFrom, $this->lonTo, $this->latTo,
$this->resolution, $this->format, $sim, $mr_id, $this->url_origin, $this->date_email));
What could be causing this behavior?
getdate() returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given.. What you are looking for is date():
$curr_date = date('Y-m-d H:i:s');
See my other question for full details.
The reason why I had this behavior is because the row was actually not getting inserted in the DAI_REQ.META_REQUEST on the first INSERT query. This was caused by the deployment server's DAI_REQ.META_REQUEST table not being set to auto increment the ID attribute.

Categories