PHP optimizing query with foreach function - php

I have this code here which is working but obviously not useful.
I've come up with this solution:
But i was getting Query empty
UPDATE:
This is the working optimization of the code
Cudos to Alex in the comments who helped me. Hope my solution help others too.
$postedids = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($postedids as $id){
$columns = array('pickup', 'delivery');
foreach ($columns as $c){
$vid = mysql_real_escape_string(trim($_POST["$c"."$id"."id"]));
$name = mysql_real_escape_string(trim($_POST["$c"."$id"."name"]));
$address = mysql_real_escape_string(trim($_POST["$c"."$id"."address"]));
$city = mysql_real_escape_string(trim($_POST["$c"."$id"."city"]));
$state = mysql_real_escape_string(trim($_POST["$c"."$id"."state"]));
$zip = mysql_real_escape_string(trim($_POST["$c"."$id"."zip"]));
$directions = mysql_real_escape_string(trim($_POST["$c"."$id"."directions"]));
$phone = mysql_real_escape_string(trim($_POST["$c"."$id"."phone"]));
if($vid!=""){
$consigneeupdate = "INSERT INTO `consignees` (`consigneeID`, `name`, `address`, `city`, `state`, `zip`, `directions`, `phone`)
VALUES ('$vid', '$name', '$address', '$city', '$state', '$zip', '$directions', '$phone')
ON DUPLICATE KEY UPDATE
`name`= CASE WHEN `consigneeID`='$vid' THEN '$name' ELSE `name` END,
`address`= CASE WHEN `consigneeID`='$vid' THEN '$address' ELSE `address` END,
`city`= CASE WHEN `consigneeID`='$vid' THEN '$city' ELSE `city` END,
`state`= CASE WHEN `consigneeID`='$vid' THEN '$state' ELSE `state` END,
`zip`= CASE WHEN `consigneeID`='$vid' THEN '$zip' ELSE `zip` END,
`directions`= CASE WHEN `consigneeID`='$vid' THEN '$directions' ELSE `directions` END,
`phone`= CASE WHEN `consigneeID`='$vid' THEN '$phone' ELSE `phone` END ";
}else{$consigneeupdate = "";}
$consignees .= mysql_query($consigneeupdate) or (mysql_error());
}
}

VALUES ('$id', '$name', '$address', '$city', '$state', '$zip', '$directions', '$phone')
Should be
VALUES ('".$id."', '".$name."', '".$address."', '".$city."', '".$state."', '".$zip."', '".$directions."', '".$phone."')

Related

Query work in PhpMyAdmin but does not work in php codes

i wrote a code that insert in two table in one time that tables connect with each other with foreign key .
i search in this site but did not find an answer .
this query worked in phpmyadmin but have false answer in php code and does not work in php ....why??? :(
this is my Query and code in php.... please help me
INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');
SELECT #Var := Last_INSERT_ID() ;
INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId )
VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', #Var)
php codes
function registerDelivery(){
$connection=createConnection();
if(!$connection){
echo "Error";
}else{
//
//get objects
//
$json = file_get_contents('php://input');
$obj = json_decode($json);
$FirstName=$obj->FirstName;
$LastName=$obj->LastName;
$PostCode=$obj->PostCode;
$IdNumber=$obj->IdNumebr;
$BirthDate=$obj->BirthDate;
$Address=$obj->Address;
$Accepted=$obj->Accepted;
$IsBike=$obj->IsBike;
$Date=$obj->Date;
$DeliverLicenseId=$obj->DriverLicenseId;
$BikeModel=$obj->BikeModel;
$PelakNumber=$obj->PelakNumebr;
$PhoneNumber=$obj->PhoneNumber;
//
//insert Query
//
$result=mysqli_query($connection,"INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');
SELECT #Var := Last_INSERT_ID() ;
INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId )
VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', #Var)");
echo json_encode(array('Result'=>$result));
mysqli_close($connection);
}
}
This is not a query but a set of multiple queries. Therefore you have to run them separately one by one:
mysqli_query($connection,"INSERT INTO ...");
$id = mysqli_insert_id($connection);
mysqli_query($connection,"INSERT INTO ...");
Note that you should be using prepared statements for your queries.
thanks all
i Edited my Queries...
function registerDelivery(){
$connection=createConnection();
if(!$connection){
echo "Error";
}else{
//
//get objects
//
$json = file_get_contents('php://input');
$obj = json_decode($json);
$FirstName=$obj->FirstName;
$LastName=$obj->LastName;
$PostCode=$obj->PostCode;
$IdNumber=$obj->IdNumebr;
$BirthDate=$obj->BirthDate;
$Address=$obj->Address;
$Accepted=$obj->Accepted;
$IsBike=$obj->IsBike;
$Date=$obj->Date;
$DeliverLicenseId=$obj->DriverLicenseId;
$BikeModel=$obj->BikeModel;
$PelakNumber=$obj->PelakNumebr;
$PhoneNumber=$obj->PhoneNumber;
//
//insert Query
//
$result=mysqli_query($connection,"INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');");
if($result){
printf ("New Record has id %d.\n", $connection->insert_id);
$id=$connection->insert_id;
if($id!=null){
$resFinall=mysqli_query($connection,
"INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId ) VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', '$id');");
echo json_encode(array('Result'=>$resFinall));
}}
it worked and insert all data in two tables ...thanks alot

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

how to insert into two tables using php with transaction?

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)

mysql query not inserting to database

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...

Categories