MySQL WHERE clause - php

Is it possible to have a WHERE clause after imploding array? I need to insert only rows where priority >=1. Thanks.
$array = array();
foreach ($priority as $priority)
$array[] = "('$id', '$studentname', '$title', '$academicdiscipline', '$priority')";
$query = "INSERT INTO flux_project_selection (id, studentname, title,
academicdiscipline, priority) VALUES ". implode(',', $array);

Insert statements shouldn't have a where clause. Instead use PHP to filter what goes into the $array variable. Here's an example:
<?php
$array = array();
foreach ($priority as $priority) {
if ($priority >=1) {
$array[] = "('$id', '$studentname', '$title', '$academicdiscipline', '$priority')";
}
}
$query = "INSERT INTO flux_project_selection (id, studentname, title,
academicdiscipline, priority) VALUES ". implode(',', $array);
?>

Related

add one element into multidimensional array

i have a not difficult question, but I couldn't find an answer.
I have a multidimensional array for insert data with one query. The result is this:
INSERT INTO table (field1, field2, field3, field4) values ('1', '2', '3'),('1', '2', '3'),('1', '2', '3'),('1', '2', '3')
and I want to add one value in each tuple like this:
INSERT INTO table (field1, field2, field3, field4) values ('1', '2', '3','10'),('1', '2', '3','10'),('1', '2', '3','10'),('1', '2', '3','10')
This is the code (I also tried with array_push inside foreach):
$DataArr = array();
for($i=1;$i<5;$i++){
$fieldVal1 = 1;
$fieldVal2 = 2;
$fieldVal3 = 3;
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";
}
$id=10;
$new=array();
foreach ($DataArr as $value) {
$value[4]="'$id'";
}
$sql = "INSERT INTO table (field1, field2, field3) values ";
$sql .= implode(',', $DataArr);
print_r($sql);
I tested this code but it doesn't work, can anyone help me?
Here is the easy solution
$DataArr = array();
for($i=1;$i<5;$i++){
$fieldVal1 = 1;
$fieldVal2 = 2;
$fieldVal3 = 3;
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";
}
$id=10;
$new=array();
foreach ($DataArr as $key =>$value) {
$tmpVal = ltrim($value,"(");
$tmpVal = rtrim($tmpVal,")");
$tmpArray = explode(',',$tmpVal);
array_push($tmpArray,'4');
array_push($new, "(".implode(',',$tmpArray).")");
}
$sql = "INSERT INTO table (field1, field2, field3, field4) values ";
$sql .= implode(',', $new);
print_r($sql);
You'd want to set the imploded data to a variable to insert and then bind the param.
$DataArr = array();
for($i = 0; $i < 4; $i++) {
$DataArr[$i] = "1,2,3";
}
$field1_arr = !empty($DataArr[0]) ? implode(",", $DataArr[0]) : "";
$field2_arr .= !empty($DataArr[1]) ? implode(",", $DataArr[1]) : "";
$field3_arr .= !empty($DataArr[2]) ? implode(",", $DataArr[2]) : "";
$field4_arr .= !empty($DataArr[3]) ? implode(",", $DataArr[3]) : "";;
$sql = $connection->prepare("INSERT INTO table (field1, field2, field3, field4) VALUES (?,?,?,?)");
$sql->bind_param("ssss", $field1_arr, $field2_arr, $field3_arr, $field4_arr);
if($sql->execute()) {
// It worked
}
$sql->close();

Construct SELECT WHERE query with array_keys and array_values in PHP

I was able to use array_keys and array_values to do an INSERT for MySQL:
$columns = implode(", ", array_keys($cmd_array));
$escaped_values = array_map( $dbc->real_escape_string, array_values($cmd_array));
$values = implode(", ", $escaped_values);
$query = "INSERT INTO cmd ($columns) VALUES ($values)";
Is there a feature to do the same thing for SELECT WHERE like this?
$query = "SELECT * FROM cmd WHERE ($columns) = ($values)";
You have to specify more than one condition using the AND or the OR operators.
So you can do this with a simple loop
$select_query = "SELECT * FROM cmd WHERE ";
$temp_array = array();
foreach($cmd_array as $key=>$val){
$temp_string = $key ." = ".$val;
array_push($temp_array, $temp_string);
}
$select_query .= implode(" AND ", $temp_array);

Writing to database using foreach

I have Three arrays and i want to write them to database , The issue I face is whenever the values are written to the particular column the rest of the column is left empty.
The
$name_array = array(3) { [0]"Name1" [1]=>"Name2" [2]=> "Name3" }
$roll_array = array(3) { [0]=>"1" [1]=>"2" [2]=>"3" }
$att_array = array(3) { [0]=>"Present" [1]=>"Present" [2]=>"absent" }
I have three columns in DB "NAME" "ROLL" "ATTENDANCE"
I want to store all the array data to the database at the same time.
so it should look like this
NAME ROLL ATTENDANCE
Name1 1 present
Name2 2 present
Name3 3 absent
Here is the code i tried but it just add each values to the column and leaves the other column empty. So the first three rows has only ROLLNO and next three row has only NAME and last three rows has only ATTENDANCE.
$name_values = array();
$roll_values = array();
$att_values = array();
foreach ($name_array as $key => $name_values) {
$name_values = mysqli_real_escape_string($connection,$name_values);
$sql= "INSERT INTO `aclass12` (Name) VALUES ('$name_values')";
mysqli_query($connection,$sql);
}
foreach ($roll_array as $key => $roll_values) {
$roll_values = mysqli_real_escape_string($connection,$roll_values);
$sql= "INSERT INTO `aclass12` (RollNo) VALUES ('$roll_values')";
}
foreach ($att_array as $key => $att_values) {
$att_values = mysqli_real_escape_string($connection,$att_values);
$sql= "INSERT INTO `aclass12` (attendance) VALUES ('$att_values')";
}
I know this is not the right way to do . and whats the way to do this ?
Simply use one array as the master, and the key of that array to access the other 2 arrays data.
Then insert all the data in a single INSERT
Its also a good idea to check that the INSERT actually worked, so I added a little bit of error checking
foreach ($name_array as $key => $value) {
$name = mysqli_real_escape_string($connection,$value);
$roll = mysqli_real_escape_string($connection,$roll_values[$key]);
$att = mysqli_real_escape_string($connection,$att_array[$key]);
$sql = "INSERT INTO `aclass12`
(Name, RollNo, attendance)
VALUES ('$value', '$roll', '$att')";
$res = mysqli_query($connection,$sql);
if ( $res === FALSE ) {
echo mysqli_error();
exit;
}
}
Use only one foreach and access the elements of the arrays there. Like this:
foreach ($name_array as $key => $name_values) {
$name_values = mysqli_real_escape_string($connection,$name_values);
$roll_values = mysqli_real_escape_string($connection,$roll_array[$key]);
$att_values = mysqli_real_escape_string($connection,$att_array[$key]);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name_values', '$roll_values', '$att_values')";
mysqli_query($connection,$sql);
}
Also, it's recommended to use prepared statements, because they prevent SQL njection attacks. More information here.
Try it this ways
for($i = 0; $i < count($name_array);$i++) {
$name_values = mysqli_real_escape_string($connection,$name_array[$i]);
$roll_values = mysqli_real_escape_string($connection,$roll_array[$i]);
$att_values = mysqli_real_escape_string($connection,$att_array[$i]);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name_values', '$roll_values','$att_values')";
}
Other option is to use multidimensional array with foreach.
foreach($name_array as $n_k=>$name) {
$roll = (isset($roll_array[$n_k])) ? $roll_array[$n_k] : '';
$att = (isset($att_array[$n_k])) ? $att_array[$n_k] : '';
$name = mysqli_real_escape_string($connection,$name);
$roll = mysqli_real_escape_string($connection,$roll);
$att = mysqli_real_escape_string($connection,$att);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name','$roll','$att')";
mysqli_query($connection,$sql);
}
I do think it would be best to use since mysql query to inject it and simply concatenate everything before that. That's something like this:
$query = "INSERT INTO tbl_name (col1, col2, col3) VALUES ";
for ($i = 0; $i < count($name_array); $i++) {
$name = mysqli_real_escape_string($conn, $name_array[$i]);
$roll = mysqli_real_escape_string($conn, $roll_array[$i]);
$att = mysqli_real_escape_string($conn, $att_array[$i]);
$query .= "('{$name}', '{$roll}', '{$att}'),";
}
$query = trim($query, ',');
$query = $query . ';';
mysqli_query($connection,$sql);
Add some damage control there (check for errors) and that's it.

How to insert mulitple POST value from array using PHP

This is my code when i ECHO out its show all POST array , but when mysqli_query action run it only insert the last value. How to insert all data in query? Can anyone help me please...
$ser = $_POST['serial'];
foreach ($ser as $seria) {
echo $serial = $seria;
}
$re = $_POST['ref_no'];
foreach ($re as $refe) {
echo $ref = $refe;
}
$des = $_POST['desc'];
foreach ($des as $desce) {
echo $desc = $desce;
}
$uni = $_POST['unitss'];
foreach ($uni as $units) {
echo $unit = $units;
}
$qt = $_POST['qty'];
foreach ($qt as $qtys) {
echo $qty = $qtys;
}
$pric = $_POST['price'];
foreach ($pric as $prices) {
echo $price = $prices;
}
$amoun = $_POST['amount'];
foreach ($amoun as $amounts) {
echo $amount = $amounts;
}
mysqli_query($con, "INSERT into purchase_order (po_id, po_no, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES ('', '".$po_nom."', '".$mr_no."', '".$serial."', '".$ref."', '".$desc."', '".$unit."', '".$qty."', '".$price."', '".$amount."', 'Pending')");
try this
$ser = $_POST['serial'];
foreach($ser as $keys=>$vals){
mysqli_query($con, "INSERT into purchase_order (po_id, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES ('', '".$vals."', '".$_POST['ref'][$keys]."', '".$_POST['desc'][$keys]."', '".$_POST['unitss'][$keys]."', '".$_POST['qty'][$keys]."', '".$_POST['price'][$keys]."', '".$_POST['amount'][$keys]."', 'Pending')");
}
or you can also do this
$ser = $_POST['serial'];
foreach($ser as $keys=>$vals){
$values_array[]="('', '".$vals."', '".$_POST['ref'][$keys]."', '".$_POST['desc'][$keys]."', '".$_POST['unitss'][$keys]."', '".$_POST['qty'][$keys]."', '".$_POST['price'][$keys]."', '".$_POST['amount'][$keys]."', 'Pending')";
}
$values=implode(",",$values_array);
mysqli_query($con, "INSERT into purchase_order (po_id, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES ".$values." ");
there's quite a big assumption here that all the arrays have the same size:
$sql='';
$n=len($_POST['serial']);
for ($i=0;$i<$n;$i++) {
$amount = $_POST['amount'][$i];
$price = $_POST['price'][$i];
$qty=$_POST['qty'][$i];
$unit=$_POST['unitss'][$i];
$desc=$_POST['desc'][$i];
$ref=$_POST['ref_no'][$i];
$serial=$_POST['serial'][$i];
$sql_part="INSERT into purchase_order (po_id, po_no, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES ('', '".$po_nom."', '".$mr_no."', '".$serial."', '".$ref."', '".$desc."', '".$unit."', '".$qty."', '".$price."', '".$amount."', 'Pending')";
$sql=$sql.';'.$sql_part;
}
mysqli_query($con, $sql);
also, note that it is not a good practice to insert data to the db directly from the $_POST variables due to SQL injections
try this
$serial = $_POST['serial'];
$ref = $_POST['ref_no'];
$desc = $_POST['desc'];
$unit = $_POST['unitss'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$amount = $_POST['amount'];
mysqli_query($con, "INSERT into purchase_order (po_id, po_no, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES ('', '".$po_nom."', '".$mr_no."', '".$serial."', '".$ref."', '".$desc."', '".$unit."', '".$qty."', '".$price."', '".$amount."', 'Pending')");
The reason that your echos show all the values is that they are each within the loop you are running to iterate through the arrays. what you are doing is overwriting the value in each of your variables inside the loop each time it steps through it, echoing it out, and then overwriting it again with the next value in the array.
you will only be able to do what you are trying to do if all arrays are the same size, you will then need to build your query string within the loop, rather than after it.
I am unfamiliar with mysqli, so I'll give you an example using PDO (this is untested and isn't meant to just plug in to your code, it's simply supposed to make the logic and the process clearer):
$con= new PDO("mysql:host=<host>;dbname=<dbName>", "dbUsr", "dbPwd");
$sql = "INSERT INTO purchase_order (po_id, po_no, serial_no, ref_no, description, unit, qty, price, amount, status) VALUES";
$masterArray = [];
for($i = 0; $i < count($_POST['serial']); $i++){
$masterArray[] = array('serial=>$_POST['serial'], 'ref_no'=>$_POST['ref_no'], 'desc'=>$_POST['desc'], 'unitss'=>$_POST['unitss'], 'qty'=>$_POST['qty'], 'price'=>$_POST['price'], 'amount'=>$_POST['amount'])
$sql .= "(?,?,?,?,?,?,?,?,?,"Pending") ";
}
$stmt = $con->prepare($sql);
$marker = 1;
foreach($masterArray as $idx=>$row){
foreach($row as $title=>$value){
$stmt->bindParam($marker, $value)
$marker++;
}
}
$stmt->execute();

PHP How add quotes?

$sqlL = '';
$Allel = '';
foreach($arr as $el){
$AllUrl .= ",'".addslashes($el)."'";
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$AllUrl = substr($Allel, 1); //delete first comma
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN($Allel);";
In result we get next $sqlL:
DELETE FROM Table WHERE ID= '4' AND URL NOT IN(house, test, test test);
But in not right and this it will not work.
Tell me please how add quotes in $Allel ?
P.S.: i would like get next query:
DELETE FROM Table WHERE ID= '4' AND URL NOT IN('house', 'test', 'test test');
Try with this:
$sqlL = '';
foreach($arr as $el){
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$AllUrl = "'".implode("','",$arr)."'";
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN($AllUrl);";
i think he wants something different , can you try it ?
implode("', '", $array);
and sql
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN('".$Allel."');";
There is only one answer to this... use prepared statements and don't build your own query using string functions and "handcraft" quotation marks and stuff. It is risky and the opposite of clean programing.
Anyways:
If $Allel contains pure values, use
$Allel = array_map(function($v) { return "'" . $v . "'"; }, $Allel);
$Allel = implode(', ', $Allel);
First line will wrap ' arround the values, second line will concat each with ,.
While using an array and implode is probably the best solution, the problem with your code is that you set up one variable with the quotes, then instead add a different variable to the SQL:-
$sqlL = '';
foreach($arr as $el)
{
$AllUrl .= ",'".addslashes($el)."'";
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$AllUrl = substr($AllUrl, 1); //delete first comma
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN($AllUrl);";
To use implode, add the items to an array (ignoring the comma), then just implode that array with a separating comma in the final assignment into the DELETE statement:-
$sqlL = '';
foreach($arr as $el)
{
$AllUrl[] = "'".addslashes($el)."'";
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN(".implode(',', $AllUrl).");";
You should be escaping the string using mysql_real_escape_string or equivalent. Not sure which database drivers you are using so although the mysql_* drivers are deprecated they will do for an example:-
$sqlL = '';
foreach($arr as $el)
{
$AllUrl[] = "'".mysql_real_escape_string($el)."'";
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN(".implode(',', $AllUrl).");";
You can use the PHP implode() function
<?php
implode(', ', $array);
PHP Documentation
You can use implode function,
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
See the example below
$array = array("1","2","3");
echo "Array is: ".implode(",",$array );
Array is: 1,2,3
try this
$sqlL = '';
$Allel = '';
$arr_Allel = array();
foreach($arr as $el){
$arr_Allel[] = ",'".addslashes($el)."'";
$sqlL .= "INSERT INTO Table (ID, Seet, Column) VALUES ('4', '$Seet', '$el');";
}
$Allel = implode(",", $arr_Allel);
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN($Allel);";
Try this:
<?php
foreach($arr as $el){
$AllUrl .= "'".addslashes($el)."' "; // Add items between spaces
}
$AllUrl_ = explode(" ",$AllUrl);
$AllUrlFinal = implode(",", $AllUrl_ ); // Change spaces by commas
$AllUrlFinal=trim($AllUrlFinal, ","); // would cut trailing and prefixing commas.
$sqlL .= "DELETE FROM Table WHERE ID= '4' AND URL NOT IN($AllUrlFinal);";

Categories