Tried everything I can think of and I've narrowed down to the "?" placeholders.
I've tried replacing the "?" placeholders with random text and all works well (except of course it keeps overwriting the same row).
The error I get:
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 '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
produ' at line 2
Here is my code (I would provide more but it all works well except for this bug, and if I remove the "?" placeholders then all works perfectly except that the values are not dynamic, but please ask if you suspect the issue is elsewhere):
// Create MySQL connection to ds_signifyd_api
$mysqli = mysqli_connect( $db_server_name, $db_username, $db_password, $db_name );
// Check connection
if ($mysqli->connect_error) {
exit( $mysqliFailedBody );
}
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = "";
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
//... more variables here...
$tags = mysqli_real_escape_string($mysqli, $tags);
if (!mysqli_query($mysqli, $mainProdQueryStmt)) {
printf("Errormessage: %s\n", mysqli_error($mysqli));
}
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
$mainProdQuery->execute();
// $mainProdQuery->close();
}
UPDATE
Implemented the fixes mentioned here:
1. Stopped using mysqli_real_escape_string
2. Binding variables outside loop
3. Using only the object oriented method, as opposed to mixing them as in the case of mysqli_query($mysqli, $mainProdQueryStmt) VS $mysqli->prepare($mainProdQueryStmt) as it should have been -- this solved the "?" placeholders syntax error being incorrectly reported
Now everything works perfectly, no errors.
Updated Code:
$mainProdQueryStmt = "INSERT INTO dss_products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$mainProdQuery = $mysqli->prepare($mainProdQueryStmt);
if ($mainProdQuery === FALSE) {
die($mysqli->error);
}
$product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = "";
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
if ($mainProdQuery) {
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
$product_title = $product['title'];
$body_html = $product['body_html'];
$vendor = $product['vendor'];
$product_type = $product['product_type'];
$created_at = $product['created_at'];
$handle = $product['handle'];
$updated_at = $product['updated_at'];
$published_at = $product['published_at'];
$template_suffix = $product['template_suffix'];
$published_scope = $product['published_scope'];
$tags = $product['tags'];
if (!$mysqli->prepare($mainProdQueryStmt)) {
printf("Errormessage: %s\n", $mysqli->error);
}
$mainProdQuery->execute();
}
}
When you use placeholders you have to use mysqli_prepare(), you can't use mysqli_query(). It looks like you intended to do that, but somehow that code got lost, since you use a variable $mainProdQuery that you never assigned.
You should prepare the query and bind the parameters just once, outside the loop. Then call execute() inside the loop.
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$mainProdQuery = $mysqli->prepare($mainProdQueryStmt);
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
//... more variables here...
$mainProdQuery->execute();
}
You're running the query before it's properly prepared, and then, after the fact, attempting to bind to something that's not the right type, it's not a statement handle but a result set. You need to structure it this way:
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
...
tags = VALUES(tags)";
// Prepare the statement to get a statement handle
$stmt = $mysqli->prepare($mainProdQueryStmt);
foreach ($dss_product_db_array as $product) {
// Bind to this statement handle the raw values (non-escaped)
$stmt->bind_param("isssssssssss",
$product['id'], $product['title'], ...);
// Execute the query
$stmt->execute();
}
Try to avoid creating heaps of throw-away variables an just bind directly to the values in question, like those in $product. The variables do nothing useful and only introduce opportunities for silly mistakes.
Try using PDO(PhP Data Objects) prepared statements. It's less painful to work with and cross database i.e can be used with any RDBMS. See PDO Official Documentation or here
Related
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.
A little background. I have an Oracle database that I am trying to query and then insert into a local MYSQL database so that I can generate canned reports. I have been trying to figure out this insert into Mysql for a while now. I have the Oracle portion running correctly but when I try to insert I have been getting a syntax error in mysql.
The result set comes back with 8 rows the first of which is the Key in MYSQL. I would really like to convert this insert query I built into a insert on duplicate key update statement but am lost on how I would do this properly. Any help you guys can provide would be appreciated.
$db1 = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=HOST)(PORT = 1521))(CONNECT_DATA=(SERVICE_NAME=Service)))';
$c1 = oci_connect("Userid", "Pass", $db1);
$sql = oci_parse($c1, "select statement") ;
oci_execute($sql);
$i = 0;
while ($row = oci_fetch_array($sql)){
$i++;
$k = $row[0];
$dte = $row[1];
$cus = $row[2];
$odr = $row[3];
$lin = $row[4];
$cas = $row[5];
$lpo = $row[6];
$cpl = $row[7];
$cpo = $row[8];
};
$db_user = "userid";
$db_pass = "Pass";
$db = new PDO('mysql:host=host; dbname=databasename', $db_user, $db_pass);
$stmt = $db->prepare("INSERT INTO `cuspi` (k, dte, cus, odr, lin, casa, lpo, cpl, cpo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$recordcount = count($k);
for ($i = 0; $i < $recordcount; $i++) {
$records[] = [
$k[$i],
$dte[$i],
$cus[$i],
$odr[$i],
$lin[$i],
$casa[$i],
$lpo[$i],
$cpl[$i],
$cpo[$i],
];
}
foreach ($records as $record) {
$stmt->execute($record);
}
?>
I was able to figure out the Answer. I was missing the grave accent around the column references for the insert.
Original
$stmt = $db->prepare("INSERT INTO `cuspi` (k, dte, cus, odr, lin, casa, lpo, cpl, cpo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
Fixed
$stmt = $db->prepare("INSERT INTO `cuspi` (`k`, `dte`, `cus`, `odr`, `lin`, `casa`, `lpo`, `cpl`, `cpo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
Product_model.php
public function addProduct($info)
{
$sql_array = array(
$info['name'],
$info['SKU'],
$info['supplier_id'],
$info['type_id'],
$info['brand_id'],
$info['added_on'],
$info['initial_cost_price']);
$this->db->trans_start();
//INSERT
$sql = "INSERT INTO
product(
name,
SKU,
supplier_id,
type_id,
brand_id,
added_on,
initial_cost_price
)
VALUES(
?,
?,
?,
?,
?,
?,
?
)
";
$query = $this->db->query($sql, $sql_array);
$insert_id = $this->db->insert_id();
$this->addProductVariant($insert_id, $info);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
return 'transaction failed';
} return TRUE;
}
public function addProductVariant($product_id, $info)
{
$sql_array = array(
$product_id,
$info['variant_name'],
$info['variant_SKU'],
$info['barcode'],
$info['wholesale_price'],
$info['buy_price'],
$info['retail_price'],
$info['description'],
$info['initial_quantity'],
$info['added_on'],
$info['last_updated']
);
$sql = "INSERT INTO
product_variant(product_id,
name,
SKU,
barcode,
wholesale_price,
buy_price,
retail_price,
description,
qty_on_hand,
created_on,
last_updated
)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$query = $this->db->query($sql, $sql_array);
}
When I hit submit on the form, the page reloads and shows this error:
Error Number: 1048
Column 'name' cannot be null
INSERT INTO product_variant(product_id, name, SKU, barcode, wholesale_price, buy_price, retail_price, description, qty_on_hand, created_on, last_updated ) VALUES(71, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2017-09-17 10:45:12', '2017-09-17 10:45:12')
Filename: D:/xampp/htdocs/svcc_inv/system/database/DB_driver.php
Line Number: 691
But when I check the database, the inserts are successful. The new records are there.
I have tried echoing the values in the $sql_array and I get correct results. I don't know why the error says they're null. I'm hypothesizing could it be because I split the whole process into two methods, one of which is inside the other, but I don't see yet how that could be.
In your example $info['variant_name'] is NULL, you need to dump $info from the start of addProduct function what does it contain, like so :
public function addProduct($info)
{
var_dump($info);
exit;
...
}
Also, I you want to use $this->db->trans_status() then you need to run transactions manually, using $this->db->trans_begin() and not $this->db->trans_start(), like so :
$this->db->trans_begin();
$sql_array = array(
$info['name'],
$info['SKU'],
$info['supplier_id'],
$info['type_id'],
$info['brand_id'],
$info['added_on'],
$info['initial_cost_price']);
$this->db->trans_start();
//INSERT
$sql = "INSERT INTO
product(
name,
SKU,
supplier_id,
type_id,
brand_id,
added_on,
initial_cost_price
)
VALUES(
?,
?,
?,
?,
?,
?,
?
)
";
$query = $this->db->query($sql, $sql_array);
$insert_id = $this->db->insert_id();
$this->addProductVariant($insert_id, $info);
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return 'transaction failed';
} else {
$this->db->trans_commit();
return true;
}
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.
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.