Inserting image into BLOB column MySQL using PHP - php

I Have Table Called XYZ
ID no no2 no3
1 465 Abc [BLOB - 15B]
2 465 Abc [BLOB - 18B]
3 465 Abc [BLOB - 80B]
4 456 Abc [BLOB - 50B]
i want to insert multiple images into "no3" using PDO
PHP
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "INSERT INTO xyz (no, no2, no3) SELECT max(nos),nos2,:tmp from ASD;
for($i=0; $i<=count($data)-1; $i++)
{
$data = $_FILES['image']['tmp_name'];
$statement = $connection->prepare($sql);
$statement->bindParam(':tmp',addslashes(file_get_contents($data[$i])));
}
$statement->execute();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
it insert only one image

As others have mentioned, you're missing a closing ", but it seems it is there in your actual code, because the behaviour you described doesn't match this syntax error.
So, looking further, you call execute only after the loop.
You will have to execute the statement over and over inside the for-loop as well.
Now you just overwrite the image in the bind parameter, call execute once, and thus only insert the last image in the database.
You should actually be able to prepare the statement once, and in the loop, for every iteration, bind a new value and execute the statement. So the code for the loop becomes this: (Assuming the details of loading the file, etc, is okay. I haven't investigated that).
$statement = $connection->prepare($sql);
for($i=0; $i<=count($data)-1; $i++)
{
$data = $_FILES['image']['tmp_name'];
$statement->bindParam(':tmp',addslashes(file_get_contents($data[$i])));
$statement->execute();
}

Correct PHP Code
$statement = $connection->prepare($sql);
$data = $_FILES['image']['tmp_name'];
for($i=0; $i<=count($data)-1; $i++)
{
$tmp = addslashes(file_get_contents($data[$i]));
$statement->bindParam(':tmp',$tmp);
$statement->execute();
}

Mate you forgot to add ending " at the of the query:
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "INSERT INTO xyz (no, no2, no3) SELECT max(nos),nos2,:tmp from ASD";
for($i=0; $i<=count($data)-1; $i++)
{
$data = $_FILES['image']['tmp_name'];
$statement = $connection->prepare($sql);
$statement->bindParam(':tmp',addslashes(file_get_contents($data[$i])));
}
$statement->execute();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}

Related

Did I do PDO right? First timer at prepared statements

Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
try{
$connection = new PDO('mysql:host=supertopsecret;dbname=supertopsecret;charset=utf8mb4',
'supertopsecret', 'supertopsecret');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Query 1 - Insert Provider's Name
//if(isset($_POST['submit'])){ delete this? do I still use this? halp
$stmt1 = $connection->prepare("INSERT INTO
`providers`(provider_first_name,provider_last_name,date_added)
VALUES (:providerfirstname, :providerlastname, NOW())");
//bind parameters:
$stmt1->bindParam(':providerfirstname', $providerfirstname);
$stmt1->bindParam(':providerlastname', $providerlastname);
//insert row
$providerfirstname = $_POST['providerfirstname'];
$providerlastname = $_POST['providerlastname'];
$stmt1->execute();
//Query 2 - Insert Practices
$prov_id = $connection->lastInsertId();
/*Get all values of practice_name[]:*/
$practicename = $_POST['practice_name'];
for ($i = 0; $i < count($practicename); $i++) {
if ($practicename[$i]) {
$practice_name_data = $practicename[$i];
$stmt2 = $connection->prepare("INSERT INTO
practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)");
$stmt2->bindParam(':prov_id', $prov_id);
$stmt2->bindParam(':practice_name', $practice_name_data);
$stmt2->execute();
}
}
echo '<center><h3><br><br><br>Thank you! Your provider has
successfully been submitted to the database!</center></h3></br>';
} catch(PDOException $e){
echo "Sorry, there was an problem submitting your provider to the
database. Please try again or copy and paste the error code below to
the \"Report a Problem\" page and we will try to correct the problem.
</b></br></br> Error: " . $e->getMessage();
die();
}
$connection = null;
You should use prepared statements instead of escaping yourself, see How can I prevent SQL injection in PHP?. But it's probably '$practicename[$i]'. It would be '{$practicename[$i]}', but easier:
foreach($practicename as $value){
if($value!=""){
$value = mysqli_real_escape_string($connection, $value);
$query2 = mysqli_query($connection,
"INSERT INTO `practices`(prov_id,practice_name)
VALUES ('$prov_id','$value')");
}
}
But again, abandon this and use Prepared Statements!
Check this it may help you. Use PDO for insert.
$connection = new PDO("mysql:host=xxxx;dbname=xxxx;", "xxxx", "xxxx"); //database connection
for ($i = 0; $i < count($practicename); $i++) {
if ($practicename[$i]) {
$practice_name_data = $practicename[$i];
$statement = $connection->prepare('INSERT INTO practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)');
$statement->bindParam(':prov_id', $prov_id);
$statement->bindParam(':practice_name', $practice_name_data);
// etc.
$statement->execute();
}
}

php/pdo insert into database mssql with arrays

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

beginTransaction in PDO

I've recently started learning about PDO.
My question is how can i execute more than 1 prepared statement.
In my example i'm trying to add a new student to the database.
The first part of the code i'm adding the student into the 'students' table.
The second part of the code i'm trying to add all of his classes (from array e.g an array(PHP,JAVA,ANGULAR)) into student_class table (which contain 2 columns - student_id and class_id).
Here's a snippet of what i've tried:
function addStudent($name, $phone, $email, $classes){
global $conn;
//first part
$stat = $conn->prepare("INSERT INTO students (sName, phone, email) VALUES(:name, :phone, :email)");
$stat->bindValue("name",$name,PDO::PARAM_STR);
$stat->bindValue("phone",$phone,PDO::PARAM_STR);
$stat->bindValue("email",$email,PDO::PARAM_STR);
$stat->execute();
//second part
//insert classes into student_class
$lastId = $conn->lastInsertId();
$conn->beginTransaction();
$len = count($classes);
for ($i=0; $i < $len; $i++) {
$cid = getClassByName($classes[$i]);//returns the class id
$cl = $conn->prepare("INSERT INTO student_class (student_id,class_id) VALUES(:sid, :cid)");
$cl->bindValue("sid",$lastId,PDO::PARAM_INT);
$cl->bindValue("cid",$cid,PDO::PARAM_INT);
$cl->execute();
}
$conn->commit();
}
try{
addStudent($params['name'], $params['phone'], $params['email'], $params['classes']);
}
catch(PDOException $e){
echo $e->getMessage();
$conn->rollback();
}
The result of this is: the user gets added to the 'students' table but the classes remain untouched (i'm getting no error), so i guess i'm doing something wrong with the second part.
I hope you can shed some light on this matter.
If these are prepared statements then you only "create" them once, and can execute them multiple times. Also edited your code to print error information, use it to debug.
function addStudent($name, $phone, $email, $classes){
global $conn;
//first part
$stat = $conn->prepare("INSERT INTO students (sName, phone, email) VALUES(:name, :phone, :email)");
$stat->bindValue("name",$name,PDO::PARAM_STR);
$stat->bindValue("phone",$phone,PDO::PARAM_STR);
$stat->bindValue("email",$email,PDO::PARAM_STR);
$stat->execute();
//second part
//insert classes into student_class
$lastId = $conn->lastInsertId();
$conn->beginTransaction();
$len = count($classes);
$cl = $conn->prepare("INSERT INTO student_class (student_id,class_id) VALUES(:sid, :cid)");
if (!$cl) {
echo "\nPDO::errorInfo():\n";
print_r($conn->errorInfo());
}
for ($i=0; $i < $len; $i++) {
$cid = getClassByName($classes[$i]);//returns the class id
$cl->bindValue("sid",$lastId,PDO::PARAM_INT);
$cl->bindValue("cid",$cid,PDO::PARAM_INT);
$cl->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $cl->errorInfo();
print_r($arr);
}
$conn->commit();
}
try{
addStudent($params['name'], $params['phone'], $params['email'], $params['classes']);
}
catch(PDOException $e){
echo $e->getMessage();
$conn->rollback();
}

two mysqli querys, one in a while loop

Can't seam to find the answer to this.
I have a mysqli loop statement. And in that loop I want to run another query. I cant write these two sql together. Is that possible?
I thought since I use stmt and set that to prepare statement. So i add another variable stmt2. Running them seperate works, but run it like I wrote it gives me "mysqli Fatal error: Call to a member function bind_param() on a non-object"
Pseudocode :
loop_sql_Statement {
loop_another_sql_statement(variable_from_firsT_select) {
echo "$first_statement_variables $second_statemenet_variables";
}
}
$sql = "select dyr_id, dyr_navn, type_navn, dyr_rase_id, dyr_fodt_aar, dyr_kommentar, dyr_opprettet, dyr_endret
from dyr_opphald, dyr, dyr_typer
where dyropphald_dyr_id = dyr_id
and dyr_type_id = type_id
and dyropphald_opphald_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i",
$p_opphald_id);
$stmt->execute();
$stmt->bind_result($dyr_id, $dyr_navn, $type_navn, $dyr_rase_id, $dyr_fodt_aar, $dyr_kommentar, $dyr_opprettet, $dyr_endret);
echo "<table>";
while($stmt->fetch()) {
echo "<tr><td>$dyr_navn</td><td>$type_navn</td><td>$dyr_rase_id</td><td>$dyr_fodt_aar</td><td>";
$sql2 = "select ekstra_ledetekst, ekstradyr_ekstra_verdi from dyr_ekstrainfo, ekstrainfo where ekstradyr_ekstra_id = ekstra_id and ekstradyr_dyr_id = ?";
try {
$stmt2 = $mysqli->prepare($sql2);
$stmt2->bind_param("i",
$dyr_id);
$stmt2->execute();
$stmt2->bind_result($ekstra_ledetekst, $ekstra_ledetekst);
echo "<td>";
while($stmt2->fetch()) {
echo "$ekstra_ledetekst => $ekstra_ledetekst<br>";
}
}catch (Exception $e) {}
echo "</td></tr>";
}
echo "</table>";
The answer:
Silly me, I didnt know I had to have two mysqli connection. So the solution was to declare another mysqli connection.
$mysqli = new mysqli($start, $name, $pwd, $selected_db);
$mysqli2 = new mysqli($start, $name, $pwd, $selected_db);
You should be able to do that, although you make have to start a second connection.

Can't use database connection while inside loop

I am having a problem with mysqli. I am trying to search a database for all people who meet a category. While looping through the results, I want to create an instance of a "Person" class, passing the database connection to the class. This is where the problem starts. Here is my code.
$con = new mysqli($db_host,$db_user,$db_password,$db_name);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
$sql = "SELECT id FROM users";
$stmt = $con->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$person = new Person( $con );
}
$stmt->close();
}
If i move the $person = new Person( $con ); to just after the while loop, it successfully makes an object of the last person. It just won't work when inside the loop. What is the reason for this?
According to error shown, you can't use the same connection until previous result set is in use. In order to make it work, you can do something like this:
$personIDs = array();
while($stmt->fetch())
{
$personIDs[] = $id;
}
$stmt->close();
and than just go through all ids buffered into array:
foreach($personIDs as $id) {
$person = new Person( $con );
}
Or, you can use store_results
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_results();
while($stmt->fetch())
{
$person = new Person( $con );
}
$stmt->free_result();
$stmt->close();
}

Categories