How incorporate On Duplicate Key with bind_param - php

Hi How can i incorporate On Duplicate Key with mysqli_stmt_bind_param
$stmt = mysqli_prepare($con, "INSERT INTO assy (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE partid=$bom");
mysqli_stmt_bind_param($stmt, "ssii", $itemid, $bom, $qty, $bomEntry) or die(mysqli_error($con));
$recordd = $tv->search(454545400000, 's=2');
//print_r($recordd);echo"1<br/>";
foreach($recordd as $data2) {
$itemid = $data2['fields']['CALC STOCK NO'];
$bomEntry = 1;
if ($data2['fields']['BOM WHEEL PN']) {
$bom = $data2['fields']['BOM WHEEL PN'];
$qty=1;
mysqli_stmt_execute($stmt) or die(mysqli_stmt_error($stmt));
$bomEntry++;
}
}
I tried something like
$stmt = mysqli_prepare($con, "INSERT INTO table_name (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE patid=$bom;");
.
.
.
but it set to blank

Your $bom is a string so it need to be quoted, or preferably swapped out of the query and bound via a placeholder. Here is the placeholder and binding approach:
$stmt = mysqli_prepare($con, "INSERT INTO assy (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE partid=?");
mysqli_stmt_bind_param($stmt, "ssiis", $itemid, $bom, $qty, $bomEntry, $bom);
With prepared statements you rarely will want variables in your query.

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.

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number

I am receiving this error and am unable to figure out why.
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\insert.php on line 32
$SELECT = "SELECT id FROM heroes WHERE name = ? LIMIT 1";
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
//Prepare statement
$stmt = $connection->prepare($SELECT);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $connection->prepare($INSERT);
$stmt->bind_param("sssss", $name, $title, $bp, $ticket, $diamond);
$stmt->execute();
echo "New hero inserted successfully, sir!";
} else {
echo "There is already a hero with this name, sir!";
}
$stmt->close();
$connection->close();
You don't actually have any params to bind in your insert:
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
Do this:
$INSERT = "INSERT INTO heroes (name, title, bp, ticket, diamond) VALUES (?, ?, ?, ?, ?)";
Then the values you bind replace the question marks.
Also note there is a very significant difference between NULL and 'NULL' -- the latter is a string. If you have an auto-incrementing ID field, just leave it out of the insert and the database will fill it in for you.

Data Not inserted in Database php, mysql

Can't insert data into DB . When i remove user_id then data is inserted. Please check below my code and help me.
function adddata($data) {
global $db;
if (is_array($data)) {
$stmt = $db->prepare('INSERT INTO `pay` (id, payment, status, itemid, time, user_id) VALUES(?, ?, ?, ?, ?, ?');
$userid = 2;
$stmt->bind_param(
'sdssss',
$data['txn_id'],
$data['payment_amount'],
$data['payment_status'],
$data['item_number'],
date('Y-m-d H:i:s'),
$userid
);
$stmt->execute();
$stmt->close();
return $db->insert_id;
}
return false;
}
It's subtle, but your SQL string is missing a closing bracket:
$stmt = $db->prepare('INSERT INTO `pay` (...) VALUES (?, ?, ?, ?, ?, ?)');
Where the VALUES list was not properly closed.
A lot of problems can be detected and resolved by enabling exceptions in mysqli so mistakes aren't easily ignored. This should show up as a SQL error in your logs.

Getting multiple errors when trying to use Prepared statements in PHP/MySQL

I am trying to use prepared statements as a best practice but I keep getting these errors.
1) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?)'
2) Undefined index: finalExamGrade in C:\wamp64 (this goes for all the superglobal variables)
3) Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\
Any fixes? Ideas?
PHP/MySQL
require_once("DBCONNECT.php");
$id = $_REQUEST['studentID'];
$last = $_REQUEST['lastName'];
$first = $_REQUEST['firstName'];
$grade1 = $_REQUEST['test1Grade'];
$grade2 = $_REQUEST['test2Grade'];
$grade3 = $_REQUEST['test3Grade'];
$grade4 = $_REQUEST['test4Grade'];
$final = $_REQUEST['finalExamGrade'];
$stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");
$stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
$stmt->execute();
var_dump($id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
$stmt->close();
$connect->close();
$stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");
The above code is the root of all of your problem.
You use SELECT to insert data. It should be INSERT.
There is an extra bracket after students table.
The total parameters doesn't match with the bind_param one. There are 7 ?
in your code when you want to store 8 variables.
Change into this code
$stmt = $connect->prepare("INSERT INTO students(col1, col2, col3, col4, col5, col6, col7, col8) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
I don't explain this code any further because it has been discussed on comments.

Is it possible to combine mysqli prepared statement with multiple inserts?

I am well-versed in the old php mysql extension.
I am working on my first script that uses the mysqli extension.
I am going to be inserting a large number of rows into a table that are being generated dynamically.
Is it possible to use a prepared statement to insert multiple rows into a table without previously knowing the number of new rows that will be inserted each time?
$stmt = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES ?, ?, ?;");
If that isn't possible, which would be more efficient:
prepared statement, one row at a time
non-prepared statement, ~50 rows at a time
// prepared statement
$stmt = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)");
for($i=0;$i<$limit;$i++)
{
$stmt->bind_param('iss', $id[$i], $name[$i], $type[$i]);
$stmt->execute();
}
// non-prepared statement
$query = "INSERT INTO `activity` (`id`, `name`, `type`) VALUES ";
for($i=0;$i<$limit;$i++)
{
$query .= "\n(".$mysqli->real_escape_string($id[$i]), $mysqli->real_escape_string($name[$i]), $mysqli->real_escape_string($type[$i])."),";
}
$query = substr($query, 0, -1).';';
PHP v.5.3.8
MySQL v. 5.1.60
$stmt = $mysqli->stmt_init();
if($stmt->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)"))
{
$stmt->bind_param('iss', $_id, $_name, $_type);
for($i=0;$i<$limit;$i++)
{
$_id = $id[$i];
$_name = $name[$i];
$_type = $type[$i];
$stmt->execute();
}
}
should do it for you!

Categories