PDO fetch not working with INSERT, UPDATE then SELECT query [duplicate] - php

This question already has answers here:
PDO multiple queries
(1 answer)
PDO Transaction statement with insert and fetch output error
(1 answer)
Closed 1 year ago.
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');
SET #bookid = LAST_INSERT_ID();
INSERT INTO paper (papername) values('hhhhhhh');
SET #paperid = LAST_INSERT_ID();
UPDATE author SET bookid = #bookid, paperid = #paperid WHERE id = 11;
SELECT #bookid as bookid, #paperid as paperid FROM DUAL;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$numofnewParn =$stmt->rowCount();
if($numofnewParn>0){
$newParentDt = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($newParentDt);
}
I have set of inserts with LAST_INSERT_ID assigned to respective parameters.
Later, updating a table with the parameters.
until $stmt->execute(); is not problem.
My question is can I continue the query by adding SELECT and fetch the data like $stmt->fetch(PDO::FETCH_ASSOC)?
or does it not make sense? if so, is there any source?
because above code does not print out.

You need to use PDOStatement::nextRowset see here to move onto the next queries result in your multi statement... however a cleaner setup would be to break this down into single statement queries and use PHP variables to save your bookid and paperid values:
<?php
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$bookid = $pdoConnect->lastInsertId();
$sql = "INSERT INTO paper (papername) values('hhhhhhh');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$paperID = $pdoConnect->lastInsertId();
$sql = "UPDATE author SET bookid = $bookid, paperid = $paperid WHERE id = 11;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();

Related

Select query not showing expected result. print_ only shows the first array correctly then a single string of other rows email field [duplicate]

This question already has an answer here:
PDO fetch returns only first row
(1 answer)
Closed 2 years ago.
A table called "checks" has fields ID;email;pass;entered;firstname;lastname;trading.
The only code in this test is the DB connection and the new PDO connection made prior to these snippets. The following snippet reports correctly that there are 5 users in the table "checks".
$sql = "SELECT COUNT(*) AS num FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo '<br>' . $row['num'] . ' users exist.';
This snippet which follows immediately after the above doesn't show the expected result.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute($id);
$users = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($users);
The print_r statement results in the first array being printed correctly with all fields/contents correctly displayed.
On the next line it prints only the email field contents from each row as a single string!
I'm probably missing something obvious but I just can't spot it. Help please?
PDO::fetch() returns a single row from the result set. You need PDO::fetchAll() instead.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC); // <--- here

why wont this query delete details from all tables? [duplicate]

This question already has an answer here:
PHP PDO how to run a multiple query request?
(1 answer)
Closed 3 years ago.
I am trying to delete records from tables matching users ID while i delete the user. but somehow it deletes records only from the cv table.
what i am trying is
if($_GET['deluser'] !='1'){
$qr = "delete from members where member_id IN(".$_GET['deluser'].")";
$qr = "delete from company where caller_id IN(".$_GET['deluser'].")";
$qr = "delete from cv where agent_id IN(".$_GET['deluser'].")";
$st = $db->prepare($qr);
$st->execute();
header('Location: users.php?action=DELETED');
exit;
what could i be doing wrong?
In your case you overwrite the value in $qr every time so you need to execute it, everyone of them separately,
you need also to fix the SQL injection problem so you can fix it
by using bind your data in the execute method or by using bindParam
first, you need to add ? with the same number of input you want to pass
you can check how it work here in this answer
$in = str_repeat('?,', count(explode(',', $_GET['deluser'])) - 1) . '?';
$qr = "delete from members where member_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from company where caller_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from cv where agent_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
You can read more about BindParam and Execute in the docs

PHP Mysql Prepared statement different result [duplicate]

This question already has answers here:
I have an array of integers, how do I use each one in a mysql query (in php)? [duplicate]
(5 answers)
mySQL bind_param with IN(?) [duplicate]
(5 answers)
Closed 3 years ago.
I have this mysql query in php:
$sql2 = "SELECT id, nazev, poradi FROM system WHERE id IN($idIs) ORDER BY poradi";
$result2 = mysqli_query($conn, $sql2);
The variable $idIs is a string '2,3' (two ids of system).
When I try to fill array $nazevSystemu, there are two values (beacause of the two ids from $idIs)
$i = 0;
$nazevSystemu = [];
while($row2 = mysqli_fetch_assoc($result2)) {
$nazevSystemu[$i] = $row2['nazev'];
echo $row2['nazev'];
$i++;
}
Result of echo $row2['nazev'];:
Value1Value2
I want to make it safe, avert SQl inj., so I use prepared statement like this (instead of the first two rows of code on this page):
$stmt2 = $conn->prepare("SELECT id, nazev, poradi FROM system WHERE id IN(?) ORDER BY poradi");
$stmt2->bind_param("s", $idIs);
$stmt2->execute();
$result2 = $stmt2->get_result();
But now I get only this as result of echo $row2['nazev']; - just one value:
Value1
What did I do wrong in prepared statement?
You have to provide all id's as individual parameters.
So instead of IN(?) you have to write IN(?,?,?) and parse each parameter individual.
Code example:
$ids = explode(',', $idIs);
$stmt2 = $conn->prepare("SELECT id, nazev, poradi FROM system WHERE id IN(".trim(str_repeat('?,', count($ids)), ',').") ORDER BY poradi");
foreach ($ids as $id) {
$stmt2->bind_param("i", $id);
}
$stmt2->execute();
$result2 = $stmt2->get_result();

How to use one stmt query inside another

i have to get data from one table from my database, BUT after getting the data, i have to access another table to get more data using the id found in the first query.
Here is my code:
$query = "SELECT id,name,datetime FROM table1 WHERE id=?";
if($stmt=mysqli_prepare($mysqli,$query)){
mysqli_stmt_bind_param($stmt,"i",$_SESSION['id']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$datetime);
while(mysqli_stmt_fetch($stmt)){
$query2 = "SELECT id FROM table2 WHERE id=?";
if($stmt2=mysqli_prepare($mysqli,$query2)){
mysqli_stmt_bind_param($stmt2,"s",$id2);
mysqli_stmt_execute($stmt2);
mysqli_stmt_store_result($stmt2);
$num = mysqli_stmt_num_rows($stmt2);
}
The code does not work, i know i can't do that. I'm new with mysqli, in MySQL it works, but in MySQLi don't.

PDO bind param in update query

I try to make prepared statament using pdo. It is possible to put several updates atonce?
Ex:
sql1 = "Update product set large = '1large' where id = 1";
sql2 = "Update product set large = '2large' where id = 2";
sql3 = "Update product set large = '3large' where id = 3";
How to prepare sql1,sql2....sqlN in Pdo to execute faster?
I found an example but it works line by line (sql1, sql2 ....)
<?php
$stmt = $dbh->prepare("UPDATE product SET large = ':large' WHERE id = ':id'");
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':large', $large, PDO::PARAM_STR);
$stmt->execute();
?>
Unlike inserts, which can be grouped into a single statement, updates are specific to an existing entry in the database.
Dependant on the broader context of what you are doing you may find a question like this of interest for bulk updates using CASE, WHEN, THEN:
Question: Update multiple rows with one query?

Categories