how to insert into two tables using php with transaction? - php

I know inserting into multiple tables with single query is not possible,
now I am trying to insert into 2 tables with php using START TRANSACTION but its not working.
my sql query is looks like
mysqli_query($con,"START TRANSACTION
INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')
INSERT INTO domains (username) VALUES ('$getuser') COMMIT");
So where is the problem??
many thanks in advance.

it is because mysqli_query can handle only one comand each time. Split them like:
mysqli_query($con, "SET AUTOCOMMIT=0");
mysqli_query($con,"START TRANSACTION");
$insert1 = mysqli_query($con,"INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')");
$insert2 = mysqli_query($con,"INSERT INTO domains (username) VALUES ('$getuser')");
if($insert1 && $insert2) {
mysqli_query($con,"COMMIT");
} else {
mysqli_query($con,"ROLLBACK");
}
mysqli_query($con, "SET AUTOCOMMIT=1");
update: if you are using mysqli the objectorientated way, you can do the following:
$mysqli->begin_transaction();
$insert1 = $mysqli->query("INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')");
$insert2 = $mysqli->query("INSERT INTO domains (username) VALUES ('$getuser')");
if($insert1 && $insert2) {
$mysqli->commit();
} else {
$mysqli->rollback();
}
HINT: if you use an older PHP version as 5.5.0, you can't use $mysqli->begin_transaction(); and have to use $mysqli->autocommit(false); at the begining and $mysqli->autocommit(true); at the end instead

Instead of
if($insert1 && $insert2)
name it just "insert" and then:
if ($insert->affected_rows > 0)

Related

My insert query only executes once

I have a registration page that works perfectly fine when it the first user registers. When the second user registers the INSERT query outputs an error. Here is my code:
if ($err_found != true)
$saveData = "INSERT INTO anc_user_info (CardNumber, UserName, Password, Name,
Surname, IDNumber, Province, Region, Branch, Gender, Language,
PhysicalAddress, Profession, Category, TelNoW, TelNoH, Email,
Cell, ProfilePic, TransactionRef, DepositAmount, DepositerName,
Declaration, UserID, Status, CreateDate)
VALUES( '$CardNumber', '$UserName', md5('$Password'), '$Name', '$Surname',
'$IDNumber', '$Province', '$Region', '$Branch', '$Gender',
'$Language', '$PhysicalAddress', '$Profession', '$Category',
'$TelNoW', '$TelNoH', '$Email', '$Cell', '$ProfilePic',
'$TransactionRef', '$DepositAmount', '$DepositerName',
'$Declaration', '$UserID', 0, NOW())" ;

Why the sql could not execute the insert query? [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Why I am getting an error when using w3school tutorial? [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to execute below code but I keep receiving below error :
"Could not execute the insert query."
It seem like the insert into Employees isn't working.
I am not sure what is missing.
Below is my code:
if(isset($_POST['submit'])) {
$fname = $_POST['fname'];
$minitial = $_POST['minitial'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$dob = $_POST['dob'];
$ssn = $_POST['ssn'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
if($fname == "" || $minitial == "" || $lname == "" || $gender == "" ||
$phone == "" || $dob == "" || $ssn == "" || $address == "" ||
$city == "" || $state == "" || $zip == "" || $email == "" ||
$username == "" || $password == "") {
echo "All fields should be filled. Either one or many fields are empty.";
echo "<br/>";
echo "<a href='register.php'>Go back</a>";}
else {
mysqli_query($mysqli, "INSERT INTO 'Employees'('fname', 'minitial', 'lname', 'gender', 'phone', 'dob', 'ssn', 'address', 'city', 'state', 'zip', 'email', 'username', 'password') VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))")
or die("Could not execute the insert query.");
echo "Registration successfully";
echo "<br/>";
echo "<a href='login.php'>Login</a>";
}
That's cause you are quoting the table name as pointed below. Don't single quote column names else it's treated as string literal rather a actual table/column name
INSERT INTO 'Employees'
You actually meant to escape it like
INSERT INTO `Employees`
Re-write your INSERT statement to be like
"INSERT INTO `Employees`(`fname`, `minitial`, `lname`, `gender`, `phone`, `dob`, `ssn`, `address`, `city`, `state`, `zip`, `email`, `username`, `password`) VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))"
Replace ' into ` or remove ' in filed list in insert query.
So you query will be
mysqli_query($mysqli, "INSERT INTO `Employees`(`fname`, `minitial`, `lname`, `gender`, `phone`, `dob`, `ssn`, `address`, `city`, `state`, `zip`, `email`, `username`, `password`) VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))")
try this query.
Because you put Table name and field name in single quote.
mysqli_query($mysqli, "INSERT INTO Employees(fname, minitial, lname, gender, phone, dob, ssn, address, city, state, zip, email, username, password) VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))")
The mysqli_error() won't solve your problem, but it will at least tell you where it is. Replace:
mysqli_query($mysqli, "INSERT INTO 'Employees'('fname', 'minitial', 'lname', 'gender', 'phone', 'dob', 'ssn', 'address', 'city', 'state', 'zip', 'email', 'username', 'password') VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))")
or die("Could not execute the insert query.");
with:
mysqli_query($mysqli, "INSERT INTO 'Employees'('fname', 'minitial', 'lname', 'gender', 'phone', 'dob', 'ssn', 'address', 'city', 'state', 'zip', 'email', 'username', 'password') VALUES('$fname', '$minitial', '$lname', '$gender', '$phone', '$dob', '$ssn', '$address', '$city', '$state', '$zip', '$email', '$username', md5('$password'))")
or die(mysqli_error($mysqli));

mysql_query is unsuccessful. The database does not receive any data

I am working on this application that is supposed to collect data from a form and send it to the database but for some reason, the database is not receiving any data. I tried using mysql_errno() and I received "Query was empty"
$name = mysql_real_escape_string($_POST['name']);
$qualification = mysql_real_escape_string($_POST['qualification']);
$position = mysql_real_escape_string($_POST['position']);
$direct = mysql_real_escape_string($_POST['direct']);
$telephone = mysql_real_escape_string($_POST['telephone']);
$cell = mysql_real_escape_string($_POST['cell']);
$fax = mysql_real_escape_string($_POST['fax']);
$email = $r['email'];
$address = mysql_real_escape_string($_POST['address']);
$cityProvince = mysql_real_escape_string($_POST['cityProvince']);
$postalCode = mysql_real_escape_string($_POST['postalCode']);
$website = mysql_real_escape_string($_POST['website']);
$q = mysql_query("INSERT INTO `mmg_business_card_logs` (`id`, `name`, `qualification`, `position`, `direct`, `telephone`, `cell`, `fax`, `email`, `address`, `cityProvince`, `postalCode`, `website`)
VALUES ('', '{$name}', '{$qualification}', '{$direct}', '{$position}', '{$telephone}', '{$cell}', '{$fax}', '{$email}', '{$address}', '{$cityProvince}', '{$postalCode}', '{$website}')");
$q = mysql_query("INSERT INTO `mmg_business_card_logs` ( `name`, `qualification`, `position`, `direct`, `telephone`, `cell`, `fax`, `email`, `address`, `cityProvince`, `postalCode`, `website`)
VALUES ('$name', '$qualification', '$direct', '$position', '$telephone', '$cell', '$fax', '$email', '$address', '$cityProvince', '$postalCode', '$website')");
OR
$q = mysql_query("INSERT INTO `mmg_business_card_logs` (`id`, `name`, `qualification`, `position`, `direct`, `telephone`, `cell`, `fax`, `email`, `address`, `cityProvince`, `postalCode`, `website`)
VALUES ('121', '$name', '$qualification', '$direct', '$position', '$telephone', '$cell', '$fax', '$email', '$address', '$cityProvince', '$postalCode', '$website')");
Try this . If this will not work try echo $q and show me the output or try to execute that query in MySql

INSERT query of xampp MySQL doesn't work

This php insert query is not working in MYSQL xampp. I couldn't find any error
QUERY:
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
you are missing $fname, $lname in query also use NULL for id if auto incremented
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES (NULL, '$username', '$fname', '$lname', '$password', '$email', '$salt' )";
you are passing wrong number of column names.your correct query should look like this:
$query = "INSERT INTO member (username,password,email,salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
You are not inserting values to all the columns specified in the query.
In your query
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
You are specifying 7 columns and only 4 values .So either add more values or remove unnecessary columns specified in the query like
$query = "INSERT INTO member (username, password,email, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
OR
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ('$id', '$username','$fname','$lname','$email', '$password', '$salt' )";

PHP Mysql Query (INSERT) Issue

I am having an issue with a MySQL query as follows:
My script generates this as an example query:
INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('Test2', '123-456-7890', 'test#test.com', 'mesa', 'az', '04-14-2013')
Which if I drop directly into PHPMyA, works fine. However, the PHP script I am trying to use to send the query from my website is not working and I can't get it figured out. Here it is:
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
mysql_query($sql);
$result = mysql_query($sql);
if($result)
{
echo("<br>Data Input OK");
}
else
{
echo("<br>Data Input Failed");
}
Nothing makes it to the MySQL DB and no PHP errors are displayed, however, if I echo $sql I get the exact query I posted previously.
Just remove the single line mysql_query($sql); on your code and you will be fine.. But you should better start practicing PHP MySQLi which stands for PHP MySQL Improved, such:
$con = mysqli_connect($host, $user, $password, $password);
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysqli_query($con, $sql);
if($result) {
echo("<br>Data Input OK");
} else {
echo("<br>Data Input Failed");
}
$sql = 'INSERT INTO Table_name (`id`, `name`) VALUES ("1", "php");
You are executing $sql twice in your script wich is causing the error, please remove
mysql_query($sql);
And it will be ready to go
I would also suggest to stop using mysql_query please switch to mysqli or PDO
Are you sure there is a valid connection (..mysql_connect())? Try using the full syntax like so..
$conn = mysql_connect(...);
$result = mysql_query($query, $conn);
Also try forcing a commit after you execute the statement -
$mysql_query("COMMIT", $conn);
You are running mysql_query twice. Reason of the error. Try running the following code.
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysql_query($sql) or die(mysql_error());
if($result){
echo("<br>Data Input OK");
} else{
echo("<br>Data Input Failed");
}
use this
"INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$_POST[name]', '$_POST[phone]', '$_POST[email]', '$_POST[city]', '$_POST[state]', '$_POST[date]')";
Try to use mysql_query($sql,$con); instead of mysql_query($sql);.
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];
$address=$_POST['address'];
$ins="insert into table_name(`name`,`age`,`address`)values('".$name."','".$age."','".$address."')";
mysql_query($ins);
echo 'data inserted successfully';
}

Categories