Php insert/update multple row, using array and not a foreach - php

I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.
I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$sql = "update ppl set firstname = $b, lastname = $c where id = $a";
The same can be said for an insert.
$sql = "insert into ppl (firstname,lastname) value ($b,$c)";
The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.
Thanks in advance.

if (count($a) <= 0)
return; // nothing to do
$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
$id = array_shift($a);
$fname = array_shift($b);
$lname = array_shift($c);
$sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma
$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";
//run your sql
this will allow you to run all of them at once.

For update you can do as follows
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$i=0;
foreach($b as $fname){
if( !empty($b[$i]))
{
$sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
}
$i++;
}
and for insert you can try
$i=0;
$var = '';
foreach($b as $fname){
if( !empty($b[$i]))
{
$var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
}
$i++;
}
if(!empty($var)){
$sql = "insert into ppl(id,firstname,lastname) values ".$var;
}

Related

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 use PDO rowCount() function in foreach?

i need some help , i have simple code like count rows in php, i use PDO ,
so i check if rowCount > 0 i do job if no other job but i have it in foreach function, in first step i get true result but in other i get invalid
so i think it is function like a closeCursor() in PDO but i try and no matter . maybe i do it wrong ?
it is part of my code
public function saveClinicCalendar($post){
$daysItm = '';
$Uid = $post['Uid'];
$ClinicId = $post['ClinicId'];
$type = $post['type'];
$resChck = '';
foreach($post['objArray'] as $arr){
foreach($arr['days'] as $days){
$daysItm = $days.",".$daysItm;
}
$daysItm = substr($daysItm, 0, -1);
$dateTime = $arr['dateTime'];
$sqlChck = 'SELECT * FROM clinic_weeks WHERE dates = :dates AND Uid = :Uid AND category = :category AND Cid = :Cid AND type = :type';
$resChck = $this->db->prepare($sqlChck);
$resChck->bindValue(":dates",$dateTime);
$resChck->bindValue(":Cid",$ClinicId);
$resChck->bindValue(":type",$type);
$resChck->bindValue(":Uid",$Uid);
$resChck->bindValue(":category",$Uid);
$resChck->execute();
$co = $resChck->rowCount();
if($co > 0){
/*UPDATE*/
$sql = 'UPDATE clinic_weeks SET dates = :dates ,time = :time, Cid = :Cid, type = :type, Uid = :Uid, category = :category ';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}else{
/*INSERT*/
$sql = 'INSERT INTO clinic_weeks (dates,time, Cid,type,Uid,category) VALUES (:dates,:time, :Cid,:type,:Uid,:category)';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}
$res->execute();
$resChck->closeCursor();
$resChck = null;
$daysItm = '';
}
}
what i am doing wrong?
many thanks to Barmar, he suggest me a true answer.
here is a code
$sql = "INSERT INTO clinic_weeks
(`timestam`,`time`,dates,Cid,type,Uid,category)
VALUES
('$timestamp','$daysItm','$dateTime','$ClinicId','$type','$Uid','$Uid')
ON DUPLICATE KEY UPDATE `time` = '$daysItm' ";
I use there "ON DUPLICATE KEY UPDATE" and it`s work perfectly!
instead a big code top of page i make a two line of code.

INSERT MySQL query not executing properly using PHP

I'm currently making a graduation website for my school where grads are supposed to submit a comment as well as submit votes for a poll.
The database has 4 tables, one for the student information, one for questions, one for comments which has a foreign key referencing snum from students and one for the poll(called survey) which has 2 foreign keys, one referencing snum again and one referencing the question id.
This is the code my seniors left for me. What it's supposed to do is create blank rows in the comments and survey tables to be updated later. However what it actually does is send everything in the comment table twice (so if there were 300 students, I would end up with 600 rows in the comments table and 0 in the survey table)
I'm still quite new to MySQL and PHP and only learned it about a month ago. If anyone can help or suggest a better way of approaching this, it would be much appreciated.
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++)
{
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('{$snum[$i]}' , NULL);";
$result = mysqli_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('{$snum[$i]}', {$qid[$a]}, NULL, NULL);";
$result = mysqli_query($link,$sql_query);
}
}
UPDATE 1:I think I found what the problem is. When I try to output $qid[$a], I get a null value. In the table, qid is a smallint unsigned, not null, auto_increment and is the primary key.
Try this code
<?php
$sql_query = "SELECT snum FROM students";
$result = mysql_query($link,$sql_query);
while ($list = mysql_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = '1' ";
$result = mysql_query($link,$sql_query);
while ($question_list = mysql_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++){
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('".$snum[$i]."' , '');";
$result = mysql_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('".$snum[$i]."','".$qid[$a]."', '', '');";
$result = mysql_query($link,$sql_query);
}
}
?>
This was solved by using mysqli_free_result($result) between the two select queries
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_assoc($result))
{
$snum[] = $list['snum'];
}
mysqli_free_result($result);
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_assoc($result))
{
$qid[] = $list['qid'];
}

How can I query to mysql with ARRAY in condition

A have names of rows in array
$arr = array(fir, seco, third);
how can I query mysql like:
$query = "SELECT * FROM $table where fir=0 and seco=0 and third=0";
but using array.
and
$query = "update $table SET fir='$ma', seco='$ma', third='$ma'";
but using array.
For search you can fire below query -
$str = implode(",", $arr);
$query = "SELECT * FROM $table where 0 IN ($str)";
But for update you have to use query what you have written.
easy,
$arr = array(fir, seco, third);
for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and " + arr[i] + "=" + $ma;
}
This is what I would do...
$fir = $arr[0];
$seco = $arr[1];
$third = $arr[2];
$query = "UPDATE $table SET $fir = '$ma', $seco = '$ma', $third = '$ma'";
Not sure if there is a more optimal answer, but you could use a for loop to create the SQL statement:
<?php
$arr = array(fir, seco, third);
$query = "SELECT * FROM $table where ";
$count = count($arr);
for($i=0;$i<$count;$i++){
$query .= ($i==$count-1) ? "$arr[$i]=0" : "$arr[$i]=0 and ";
}
echo $query;
?>
Echoes SELECT * FROM $table where fir=0 and seco=0 and third=0. You can do the same with the UPDATE SQL statement.
Update
Also, you could implode the array, like in Suresh Kamrushi's answer, and use the following code:
<?php
$arr = array(fir, seco, third);
$str = implode(',',$arr);
$query_one = "SELECT * FROM $table WHERE ($str) = (0,0,0)";
echo $query_one;
?>
The UPDATE query would still need a for loop though, I think.

Insert array to mysql database php

I want to add an array to my db. I have set up a function that checks if a value in the db (ex. health and money) has changed. If the value is diffrent from the original I add the new value to the $db array. Like this $db['money'] = $money_input + $money_db;.
function modify_user_info($conn, $money_input, $health_input){
(...)
if ($result = $conn->query($query)) {
while ($user = $result->fetch_assoc()) {
$money_db = $user["money"];
$health_db = $user["health"];
}
$result->close();
//lag array til db med kolonnene som skal fylles ut som keys i array
if ($user["money"] != $money_input){
$db['money'] = $money_input + $money_db;
//0 - 20
if (!preg_match("/^[[0-9]{0,20}$/i", $db['money'])){
echo "error";
return false;
}
}
if ($user["health"] != $health_input){
$db['health'] = $health_input + $health_db;
//0 - 4
if (!preg_match("/^[[0-9]{0,4}$/i", $db['health'])){
echo "error";
return false;
}
if (($db['health'] < 1) or ($db['health'] > 1000))
{
echo "error";
return false;
}
}
The keys in $db represent colums in my database. Now I want to make a function that takes the keys in the array $db and insert them in the db. Something like this ?
$query = "INSERT INTO `main_log` ( `id` , ";
foreach(range(0, x) as $num) {
$query .= array_key.", ";
}
$query = substr($query, 0, -3);
$query .= " VALUES ('', ";
foreach(range(0, x) as $num) {
$query .= array_value.", ";
}
$query = substr($query, 0, -3);
$query .= ")";
If the id field is already set to be an Auto-Increment value, you do not need to declare it in the INSERT command (it is just assumed as not being over-ridden, and will fill with the auto-incremented value).
Assuming that $db is an an associative array, where the element keys are the same as the SQL field names, and the element values are the desired values for those SQL fields.
# Sanitise the Array
$db = array_map( 'mysql_real_escape_string' , $db )
# Create the SQL Query
$query = 'INSERT INTO `main_log` '.
'( `'.implode( '` , `' , array_keys( $db ) ).'` ) '.
'VALUES '.
'( "'.implode( '" , "' , $db ).'" )';
That should produce an SQL query which will perform the required work. Plus it should reduce the possibility of SQL Injection attacks...
(Note: The line breaks, etc. above are for readibility only, and can be removed.)

Categories