Catch Duplicate entry with prepared SQL statement - php

I want to handle the "Duplicate entry" error with a prepared MySQL statement.
I have thoses lines
$result = $db->prepare("INSERT INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
$result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date));
And want to execute some code if there is not any error. And display a pop-up and make the prog die if there is an error.
I already tried
if($result === false)//Catch error
{}
else //It worked
{}
But it did not worked

You can use INSERT IGNORE and then check how many rows were affected using PDOStatement::rowCount
Concept should be along the lines of:
$result = $db->prepare("INSERT IGNORE INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
if ($result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date))) {
if ($result->rowCount() == 0) {
// You had a duplicate record.
} else {
// all good.
}
}

Related

SQL Prepared statement not inserting my values

I have this prepared statement and it isn't inserting into the table at all. The connection to my database is working. I am still new to this so I am unsure on what is wrong. The spelling of my table is correct also. My network tab on inspect element doesn't show any errors as if it did insert the data but the table doesn't update with said data.
$stmt = $conn->prepare("INSERT INTO usersreports (DateOfReport,Username,ReportedPostId,ReportedUser,ReportedUserId,ReportedReason,ReportedTopic,Resolved,Response,ActionTaken) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $DateOfReport,$YourUsername,$UsersPostId,$ReportedUsername,$ReportedUserId,$ReportReason,$ReportTopic,$Resolved,$Response,$ActionTaken);
if ( $stmt === false ) {
echo $conn->error;
exit;
}
$stmt->execute();
$stmt->close();
$conn->close();

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.

PDOStatement::execute(): SQLSTATE[HY093] , strange behavour during bulk insert

Can someone help? I am trying to do a bulk insert (400 rows), everytime it shows an error message after inserted 58 rows in the database, I tried different dataset, it behave the same way.
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here is the Code:
$rows = $_POST['myTableArray'];
$nrecuser= $_SERVER['REMOTE_ADDR'];
$ndatetime= date('Y-m-d G:i:s');
$sql = "INSERT INTO dbo.rec(ncode, nname, nprimary, ndate, nyear, nperiod,
nref, ntype, nuser, ncategorycode1, ncategorycode2,
ncategorycode3, namount, ndescription, naccount,
nmajorheadcode, ncheck, nrecuser, ndatetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
include_once dirname(__FILE__) . '/includes/db.inc.php';
try
{
$conn->beginTransaction();
$stmt = $conn->prepare($sql);
foreach($rows as $row)
{
array_push($row, $nrecuser, $ndatetime);
$stmt->execute($row);
}
$conn->commit();
exit();
}
catch (PDOException $e)
{
$conn->rollback();
echo $e;
exit();
}
The number of given insert query parameters is not equal values you are passing to insert
It turn out to be a server side issue, all I have to update the php.ini max_input_vars setting. Thanks for the help.

Can't Insert data in MySql Table, but i can retrieve data just fine

I can conect to my database just fine, but whenever I try to insert data I get a "Call to a member function bind_param() on a non-object" error, which I know means that I must have mistyped the name of a slot, or something, but I just can't see it, I'm connecting locally, do I have to set up something in MyPhP to allow data to be added from a php file? Thanks in advance.
<?php
include 'connect.php';
if (isset($_POST['Slot1'])) {
$Slot1 = $_POST['Slot1'];
}
if (isset($_POST['Slot2'])) {
$Slot2 = $_POST['Slot2'];
}
if (isset($_POST['Slot3'])) {
$Slot3 = $_POST['Slot3'];
}
if (isset($_POST['Slot4'])) {
$Slot4 = $_POST['Slot4'];
}
if (isset($_POST['Slot5'])) {
$Slot5 = $_POST['Slot5'];
}
if (isset($_POST['Slot6'])) {
$Slot6 = $_POST['Slot6'];
}
if (isset($_POST['Slot7'])) {
$Slot7 = $_POST['Slot7'];
}
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?");
$stmt->bind_param('sssssss',$Slot1,$Slot2,$Slot3,$Slot4,$Slot5,$Slot6,$Slot7);
$stmt->execute();
$stmt->close();
header("Location: Display.php")
?>
You have missed one end parenthese
Replace
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?");
To
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?)");
Try to change your query to
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,Slot6, Slot7)VALUES (?, ?, ?, ?, ?, ?,?)");

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

Categories