I have a project file, and i have trouble at my syntax, example:
mysqli_query($connection,"START TRANSACTION");
$mysql_query = mysqli_multi_query($connection,"
INSERT INTO `TABLE 1` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 1');
INSERT INTO `TABLE 2` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 2');
INSERT INTO `TABLE 3` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 3');
");
if(!$mysql_query){
echo "Syntax MySQL: " . mysqli_error($connection);
}else{
do{
// Store first result set
if ($result=mysqli_store_result($connection)){
mysqli_free_result($result);
}
}while (mysqli_next_result($connection));
}
if imposible, i want to rollback if one MySQL Query is failed to inserted, i think we can check one by one for this query,
thanks for advance!.
It should be something like this:
mysqli_autocommit($connection, FALSE);
$mysql_query = mysqli_multi_query($connection,"
INSERT INTO `TABLE 1` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 1');
INSERT INTO `TABLE 2` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 2');
INSERT INTO `TABLE 3` (`ID`, `VAL`) VALUES (NULL, 'NAMBAH 3');
");
do{
// Store first result set
if ($result=mysqli_store_result($connection)){
mysqli_free_result($result);
}
}while (mysqli_next_result($connection));
if( $mysqli_errno($connection)){
$mysqli_commit($connection);
}else{
echo "MySQL Error: " . mysqli_error($connection);
$mysqli_rollback($connection);
}
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
PHP
<?php
$server_name= "localhost";
$db_user="root";
$db_password="";
$db_name="digitalmarketing";
$connection=mysqli_connect($server_name,$db_user,$db_password,$db_name);
$dbconfig=mysqli_select_db($connection,$db_name);
session_start();
$_SESSION['message']='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
$title= mysqli_real_escape_string($connection,$_POST['title']);
$Des= mysqli_real_escape_string($connection,$_POST['des']);
$imagepath= mysqli_real_escape_string($connection,'Projects/'.$_FILES['filename']['name']);
$link= mysqli_real_escape_string($connection,$_POST['link']);
echo $title," ";
echo $Des," ";
echo $imagepath," ";
echo $link," \n ";
if(preg_match("!image!",$_FILES['filename']['type'])){
if(copy($_FILES['filename']['tmp_name'],$imagepath)){
$query="INSERT INTO `project` (`id`, `Title`, `Description`, `Image`, `Site`) VALUES (NULL, $title, $Des, $imagepath, $link)";
if(mysqli_query($connection, $query))
{
echo "success";
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($connection);
}
}
}
}
Error
Error: INSERT INTO project (id, Title, Description, Image, Site) VALUES (NULL, TitleHere, DescripHere, Projects/Screenshot 2021-03-18 222903.png, https://www.w3schools.com/tags/att_input_type.asp)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2021-03-18 222903.png, https://www.w3schools.com/tags/att_input_type.asp)' at line 1
Why am I getting this error?
Change
$query="INSERT INTO `project` (`id`, `Title`, `Description`, `Image`, `Site`) VALUES (NULL, $title, $Des, $imagepath, $link)";
to
$query="INSERT INTO `project` (`id`, `Title`, `Description`, `Image`, `Site`) VALUES (NULL, '$title', '$Des', '$imagepath', '$link')";
Extra: Read about using prepared statements and use it.
https://www.tutorialrepublic.com/php-tutorial/php-mysql-prepared-statements.php
I'm new in using transaction. My previous problem is about multiple inserts that should abort if one encounters an error and transaction with ignore solves it. My new problem is that I have to know if the insert is successful and if not should display the error.
PROFILE table
+--+----+---------+
|ID|NAME|BAL_LIMIT|
+--+----+---------+
NUMBER table
+--+----------+------+
|ID|PROFILE_ID|NUMBER|
+--+----------+------+
--TRANSACTION STATEMENT--
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, "Name", 0);
INSERT INTO `NUMBER` (`PROFILE_ID`, `NUMBER`) VALUES(LAST_INSERT_ID() , "09123456789");
COMMIT;
--ERROR TO BE HANDLED--
#1062 - Duplicate entry '09123456789' for key 'NUMBER_UNIQUE'
--PHP file contains--
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$execute_transaction = mysqli_multi_query($con,$transaction) or die("Error: ".mysqli_error($connection));
if (!$execute_transaction) {
echo mysqli_error($connection);
} else { echo "success"; }
The PHP file always shows success though having #1062 error and the inserts are ignored.
Multi-queried transaction statement problem solved.
Final PHP file:
<?php
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$aff_rows = 0;
if(mysqli_multi_query($con,$transaction)){
do{$aff_rows+=mysqli_affected_rows($con);
}while(mysqli_more_results($con) && mysqli_next_result($con));
}if($aff_rows==2){//SUCCESS
echo "<script>swal(\"$vname\", \"New number: $vnumber\", \"success\");</script>";
}if($aff_rows==1){//WRONG NUMBER CORRECT NAME
echo "<script>swal(\"Duplicate entry of $vnumber\", \"Failed to add for: $vname\", \"error\");</script>";
}if($aff_rows==0){//WRONG NAME CORRECT/WRONG NUMBER
echo "<script>swal(\"Duplicate entry of $vname\", \"Failed to add number: $vnumber\", \"error\");</script>";}
?>
$sql = "INSERT INTO 'testdatabase`.`newuserformtable' (`First Name`,`Last Name`, `Title`)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
I've tried everything and I still get this error message:
Connected successfullyError: INSERT INTO 'testdatabase`.`newuserformtable`(`First Name`, `Last Name`, `Title`) VALUES ('John', 'Doe', 'john#example.com')
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 ''testdatabase`.`newuserformtable' (`First Name`, `Last Name`, `Title`) VALUES ' at line 1
The problem was with your single quotes (') and back-ticks (`) in your query. Try using this below, I could not put it in comment
INSERT INTO `testdatabase`.`newuserformtable` ...
Database name or table name should not be considered as a string.
so the sql should be :
INSERT INTO testdatabase.newuserformtable (`First Name`,`Last Name`, `Title`)
VALUES ('John', 'Doe', 'john#example.com');
It seems error with single quote you mixed with
$sql = "INSERT INTO `testdatabase`.`newuserformtable' (`First Name`,`Last Name`, `Title`)
VALUES ('John', 'Doe', 'john#example.com')";
$sql = "INSERT INTO testdatabase.newuserformtable' (First Name,Last Name,Title`)
VALUES ('John', 'Doe', 'john#example.com')";
write like this problem with your quotes.....and also checkdatatype and length
if there is another error post your error
You used a single quote(') instead of a backtick(`) on the database and table name.
$sql = "INSERT INTO `testdatabase`.`newuserformtable`
(`First Name`,`Last Name`, `Title`)
VALUES
('John', 'Doe', 'john#example.com')";
$sql = "INSERT INTO `testdatabase`.`newuserformtable'
(`First Name`,`Last Name`, `Title`)
VALUES
('John', 'Doe', 'john#example.com')";
$res = mysql_query($sql);
if ($res) {
echo "New record created successfully";
}
else {
echo "Error";
}
I am using php and trying to add a item to my MySQL database.
If I use the following code it works:
mysql_query("INSERT INTO `intranet`.`product_form` (`id`, `ProductName`, `ProductInitiatedBy`) VALUES (NULL, 'item1', 'item2')") or die("Could not perform select query - " . mysql_error());;
However, if I use the following code it doesn't work:
$product_name=("tom");
mysql_query("INSERT INTO `intranet`.`product_form` (`id`, `ProductName`, `ProductInitiatedBy`) VALUES (NULL, $product_name, 'item2')") or die("Could not perform select query - " . mysql_error());;
I get an error that says:
Could not perform select query - Unknown column 'ProductName1234' in
'field list'
The ProductName1234 is the data from $product_name and should be the data I am trying to add and not the column.
When you insert strings like that, you need to surround them in quotes, else MySQL will think you are trying to specify a column from somewhere to insert data from.
mysql_query("INSERT INTO intranet.product_form (id, ProductName, ProductInitiatedBy) VALUES (NULL, \"$product_name\", 'item2')");
Change:
mysql_query("INSERT INTO `intranet`.`product_form` (`id`, `ProductName`, `ProductInitiatedBy`) VALUES (NULL, $product_name, 'item2')") or die("Could not perform select query - " . mysql_error());;
to:
mysql_query("INSERT INTO `intranet`.`product_form` (`id`, `ProductName`, `ProductInitiatedBy`) VALUES (NULL, '$product_name', 'item2')") or die("Could not perform select query - " . mysql_error());
You need to add ' to $product_name:
VALUES (NULL, '$product_name', 'item2')
^ ^
i have a db query in php that is not inserting into database. Have used this format lots of times but for some reason its not working now. any ideas please
$query = "INSERT INTO `databasename`.`member_users` (`id`, `first_name`, `last_name`, `username`, `password`, `address1`, `address2`, `postcode`, `access`, `expires`) VALUES (NULL, '$fname', '$lname', '$email', '', '$add1', '$add2', '$postcode', '0', '')";
$result = mysql_query($query);
if($result){
echo"query inserted";
}else{
echo "nope";
}
Instead of echo "nope"; I suggest something like :
echo 'error while inserting : ['.mysql_errno().'] '.mysql_error();
echo 'query : '.$query;
This way you will be able to see the exact error and the query that was executed.
It can be a lot of things :
Constraint error with a foreign key
Data type error
Non-existent field
Wrong database or table name
Instead of...
$query = "INSERT INTO `databasename`.`member_users` ..."
do
$query = "INSERT INTO member_users ..."
Hope it works. :)
If databasename and member_users are variables then,
Instead of
$query = "INSERT INTO databasename.member_users...
do
$query = "INSERT INTO $databasename.$member_users...