Insert into mySQL from php foreach loop [duplicate] - php

This question already has answers here:
How to insert multiple rows using prepared statements
(1 answer)
Best way to INSERT many values in mysqli?
(4 answers)
Closed 4 months ago.
I know this has been asked so many times but I can't seem to figure the issue out. Im running the following code, but it just returns the fail. When I run the output of
$query1 --> INSERT INTO number (count,code,prize,printed) VALUES ('1','Q0stZr0g8uc4syE','','0');
straight into phpmyadmin it inserts fine. I must be doing something stupid... Any ideas?
$times_to_run = 100;
$prize='';
for($i=1;$i<=$times_to_run;$i++){
$array[] = array(
'count' => $i,
'code1' => randomString(),
'prize' => $prize
);
}
$codes = $array;
foreach ($codes as $code){
$query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0');";
$q = mysqli_query($query1) or die (mysql_error());
}
EDIT: I changed the query to use mysqli and got the full error which is:
the actual error is:
Warning: mysqli_query() expects at least 2 parameters, 1 given and the line it points to is: $q = mysqli_query($query1) or die (mysql_error());
** If I change
'". $code['prize']."'
to '0' I still get the same error.

To make things clear, here is the corrected version of your code:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$times_to_run = 100;
$prize='';
for($i=1;$i<=$times_to_run;$i++){
$array[] = array(
'count' => $i,
'code1' => randomString(),
'prize' => $prize
);
}
$codes = $array;
foreach ($codes as $code){
$query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0')";
$q = mysqli_query($link, $query1) or die (mysqli_error($link));
}

I might be wrong here but I think there are spaces needed after ] and after that .
Like this:
'" . $code['count'] . "'
instead of
'". $code['count']."'
Oh and just something that might be handy and good to know, mysql_query is deprecated and unsafe, unles you are using it for yourself at a local host I would suggest you take a look at mysqli_, which works basicly the same.
http://php.net/manual/en/function.mysql-query.php

Related

I'm Unable to perform a PHP insert query

I'm trying to insert the data in a MYSQL database but it seems that my query is not working i've tried all other methods but nothing is working for me ,Here is the PHP that i'm using
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$a= mysql_real_escape_string($_POST['doctorname']);
$b = mysql_real_escape_string($_POST['writtendate']);
$c = mysql_real_escape_string($_POST['hospitalname']);
$d = mysql_real_escape_string($_POST['patientname']);
$e = mysql_real_escape_string($_POST['dateofbirth']);
$f= mysql_real_escape_string($_POST['cardnumber']);
$g = mysql_real_escape_string($_POST['groupname']);
$h = mysql_real_escape_string($_POST['drug1']);
$i = mysql_real_escape_string($_POST['drug2']);
$j = mysql_real_escape_string($_POST['drug3']);
$k = mysql_real_escape_string($_POST['drug4']);
$l = mysql_real_escape_string($_POST['amount1']);
$m = mysql_real_escape_string($_POST['amount2']);
$n = mysql_real_escape_string($_POST['amount3']);
$f = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query="insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3) values ('$_POST[doctorname]','$_POST[writtendate]','$_POST[hospitalname]','$_POST[patientname]','$_POST[dateofbirth]','$_POST[cardnumber]','$_POST[groupname]','$_POST[principalmembersname]','$_POST[drug1]','$_POST[drug2]','$_POST[drug3]','$_POST[drug4]','$_POST[amount1]','$_POST[amount2]','$_POST[amount3]')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
To get you on the right track on using PDO and prepared statements (with named placeholders in this case):
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
$statement = $pdo->prepare("INSERT INTO `uap` (`doctorname`,`writtendate`,`hospitalname`,`patientname`,`dateofbirth`,`cardnumber`,`groupname`,`principalmembersname`,`drug1`,`drug2`,`drug3`,`drug4`,`amount1`,`amount2`,`amount3`) VALUES (:doctorname, :writtendate, :hospitalname, :patientname, :dateofbirth, :cardnumber, :groupname, :principalmembersname, :drug1, :drug2, :drug3, :drug4, :amount1, :amount2, :amount3)");
$result = $statement->execute(
array(
'doctorname' => $_POST['doctorname'],
'writtendate' => $_POST['writtendate'],
'hospitalname' => $_POST['hospitalname'],
'patientname' => $_POST['patientname'],
'dateofbirth' => $_POST['dateofbirth'],
'cardnumber' => $_POST['cardnumber'],
'groupname' => $_POST['groupname'],
'principalmembersname' => $_POST['principalmembersname'],
'drug1' => $_POST['drug1'],
'drug2' => $_POST['drug2'],
'drug3' => $_POST['drug3'],
'drug4' => $_POST['drug4'],
'amount1' => $_POST['amount1'],
'amount2' => $_POST['amount2'],
'amount3' => $_POST['amount3']
)
);
if (!$result)
{
echo "SQL Error <br/>";
echo $statement->queryString."<br/>";
echo $statement->errorInfo()[2];
}
Although I still think your schema could use some optimization (eg. a dedicated drug table with a many-to-many relation to patients or whatever this is)
The problem with the code that you have above mainly lies in string concatenation. In your $query variable you have two primary issues:
First you have combined array syntax within a quoted string:
$query = "insert into uap (...) values ('$_POST[doctorname]')"
Second the when you reference arrays like $_POST[doctorname] (without the quotes around the keys) PHP assumes that the unquoted string is a constant that contains the same value as its name. That makes this seem like proper code, but it is actually very, VERY messy.
The PHP interpreter cannot understand exactly what you are trying to do in this case and ends up stopping concatenation at the $_POST variable. So your resultant string probably looks something like this: insert into uap (...) values ('array[doctorname]'). You can correct this by using braces to tell the PHP interpreter to use the whole array syntax in the string:
$query = "insert into uap (...) values ('{$_POST['doctorname']}')" or by using the concatenation . operator to perform proper string concatenation: $query = 'insert into uap (...) values ('".$_POST['doctorname']."')".
You simplest solution however, is to use the variables that you had specified above in your code. You final $query variable should look something like this (which will also use the `mysql_escape_string() function that you used above):
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$doctorname = mysql_real_escape_string($_POST['doctorname']);
$writtendate = mysql_real_escape_string($_POST['writtendate']);
$hospitalname = mysql_real_escape_string($_POST['hospitalname']);
$patientname = mysql_real_escape_string($_POST['patientname']);
$datofbirth = mysql_real_escape_string($_POST['dateofbirth']);
$cardnumber = mysql_real_escape_string($_POST['cardnumber']);
$groupname = mysql_real_escape_string($_POST['groupname']);
$drug1 = mysql_real_escape_string($_POST['drug1']);
$drug2 = mysql_real_escape_string($_POST['drug2']);
$drug3 = mysql_real_escape_string($_POST['drug3']);
$drug4 = mysql_real_escape_string($_POST['drug4']);
$amount1 = mysql_real_escape_string($_POST['amount1']);
$amount2 = mysql_real_escape_string($_POST['amount2']);
$amount3 = mysql_real_escape_string($_POST['amount3']);
$principlemembersname = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query = "insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3)
values ('$doctorname','$writtendate','$hospitalname','$patientname','$datofbirth','$cardnumber','$groupname','$principlemembersname','$drug1','$drug2','$drug3','$drug4','$amount1','$amount2','$amount3')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
As noted by other users it would be a good idea to convert this code to use PDO and prepared statements as the mysql functions in PHP are deprecated.
Good luck! I hope this helps!

Wordpress mysql_fetch_array() expects parameter 1 to be resource error

Very new to using mysql, however, I'm trying to fix a bug in an old piece of code in a wordpress plugin - here is the original code:
$sql = mysqli_query("SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'") or die(mysql_error());
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10 );
if($row = mysql_fetch_array($sql)) {
$qry = $row['Qcount'];
}
if($qry >= $no_of_questions) {
$value = "The question limit for today has been reached";
$button = "disabled";
} else {
$value = "Add your question to the cart";
$button = " ";
}
Which was giving the following error:
mysqli_query() expects at least 2 parameters, 1 given in
I have since changed the first line as follows to use Wordpress functions:
$sql = $wpdb->get_results( "SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'" );
which now gives the following errors:
mysql_fetch_array() expects parameter 1 to be resource, array given in ...
Undefined variable: qry in ...
Is there something obvious that I am doing wrong here?
You should make mysqli connection first and then use queries and fetch queries further. You can follow the below link to use mysqli fetch queries.
https://www.w3schools.com/php/func_mysqli_fetch_array.asp
You're mixing things up.
mysql_ and mysqli_ are two completely different sets of functions in PHP. You can't send a query using the mysqli_ function, and manipulate the results with mysql_*.
Also, mysql_ functions were deprecated in later versions of PHP5, and removed altogether in PHP7.
Your best bet is to follow #tadman's advice and use WP's API for this.
Is the only line you changed the $sql = line?
From the wordpress codex:
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
should return you an array or object of results per the documentation.
so your code wouldn't need to do any of the fetch_assoc related methods. Wordpress is handling the actual DB connection and query parsing and just handing you back your results.
Possible Solution:
// formatting for readability.
$date = date("Y-m-d");
// Prepare query.
$sql = $wpdb->prepare(
"SELECT count(`question_count`) as Qcount
FROM `wp_posts`
WHERE `question_count` = 1
AND `question_date` = %s",
$date
);
// Execute query.
$results = $wpdb->get_results($sql);
// Get option for number of questions.
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10);
// Set base values to avoid usage of else condition.
$value = "Add your question to the cart";
$button = " ";
// Check to ensure results returned.
if (!empty($results)) {
// Evaluate result of query.
if ($results[0]->Qcount >= $no_of_questions) {
// Update values only if necessary.
$value = "The question limit...";
$button = "disabled";
}
}

mysql data insertion with foreach loop

I was inserting records successfully with this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
rep_date = '$dt'";
But now I have two extra fields in my table, remark and nor. So now, for inserting all data I made this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
remark = '**$remark**',
nor = '**$nor**',
rep_date = '$dt'";
I did not get anything in the database. Not everything is ok here. If I use only one if condition then data is being inserted like (rep_result,remark,nor any one).
if(strstr($k, 'remark_'))
$remark=$v;
But when I use all the three condition, nothing is stored. I know I have ifstatement or foreach loop problem.
As others have said, your SQL syntax is fundamentally incorrect (mixing INSERT and UPDATE syntax). A single row insert statement would have a structure like this:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '$test_id', '$content', '$R[payment_id]', '$dt' )
Do read up on prepared statements, MySQLi and PDO to learn more about performance and efficient use of the database server.
Also, just in a general sense, sending numerous independent SQL statements to the database from within a loop is potentially a huge performance issue. There is communication and connection overhead associated with each one of those calls that has nothing to do with the actual data insertion work that you want to the database server to perform.
MySQL allows you to insert multiple rows with the same statement, so you could build up a single SQL statement in your loop, then send all the inserts in one call to the database.
The syntax to insert multiple rows with one statement looks like:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '1', 'Row 1 content', '1', '2013-04-15' ),
( '2', 'Row 2 content', '2', '2013-04-15' ),
( '3', 'Row 3 content', '3', '2013-04-15' ),
( '4', 'Row 4 content', '4', '2013-04-15' );
For documentation and more examples, see:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
https://stackoverflow.com/a/6889087/618649
https://stackoverflow.com/a/1307652/618649
Your INSERT query statment has mistakes.
I can't test your code but i assume your condition works here is a sample of mysqli connection and INSERT query.
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report (`rep_te_id`, `rep_result`, `record_id`, `remark`, `nor`, `rep_date`) VALUES ('".$test_id."', '".$content."', '".$R['payment_id']."', '".$remark."', '".$nor."', '".$dt."')";
echo $SQL //let's see the query
$mysqli->query($SQL) or die($msqli->error.__LINE__);
}
}
}
}
as you see i placed an echo right after the $SQL statement to see if your condition are matched. If the query will not be printed so yuo have problem with all those if condition
hey buddy your insert query syntax is wrong user correct and learn some sql query syntax
INSERT INTO report (rep_te_id,rep_result,remark,nor,rep_date) VALUES ('$test_id','$content','$R[payment_id]','**$remark**','**$nor**','$dt');
Try implement an else for each of your if condition and try echoing something from their, because look like any of your If condition is not getting satisfied.
I would suggest you to echo $k only from all three else because you will be able to know current value of $k.
also specify else no. in echo so you will be able to get which else got called.

php push 2d array into mysql

Hay All,
I cant seem to get my head around this dispite the number to examples i read. Basically I have a 2d array and want to insert it into MySQL. The array contains a few strings.
I cant get the following to work...
$value = addslashes(serialize($temp3));//temp3 is my 2d array, do i need to use keys? (i am not at the moment)
$query = "INSERT INTO table sip (id,keyword,data,flags) VALUES(\"$value\")";
mysql_query($query) or die("Failed Query");
Thanks Guys,
Not sure it's be a full answer to your question, but here at least a couple of possible problems :
You should not use addslashes ; instead, use mysql_real_escape_string
It knows about the things that are specific to your database engine.
In your SQL query, you should not use double-quotes (") arround string-values, but single-quotes (')
In your SQL query, you should have as many fields in the values() section as you have in the list of fields :
Here, you have 4 fields : id,keyword,data,flags
but only one value : VALUES(\"$value\")
You should use mysql_error() to know what was the precise error you've gotten while executing the SQL query
This will help you find out the problems in your queries ;-)
<?php
// let's assume we have a 2D array like this:
$temp3 = array(
array(
'some keywords',
'sme data',
'some flags',
),
array(
'some keywords',
'sme data',
'some flags',
),
array(
//...
),
);
// let's generate an appropriate string for insertion query
$aValues = array();
foreach ($temp3 as $aRow) {
$aValues[] = "'" . implode("','", $aRow) . "'";
}
$sValues = "(" . implode("), (", $aValues) . ")";
// Now the $sValues should be something like this
$sValues = "('some keywords','some data', 'someflags'), ('some keywords','some data', 'someflags'), (...)";
// Now let's INSERT it.
$sQuery = "insert into `my_table` (`keywords`, `data`, `flags`) values $sValues";
mysql_query($sQuery);
As an addition to the useful answers already given, if you have a big table that you need to insert it might not fit in one SQL statement. However, making a separate transaction for each row is also slow. In that case, we can tell MySQL to process multiple statements in one transaction, which will speed up the insertion greatly for big tables (>1000 rows).
An example:
<?php
function dologin() {
$db_username = 'root';
$db_password = 'root';
$db_hostname = 'localhost';
$db_database = 'logex_test';
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database);
}
function doquery($query) {
if (!mysql_query($query)) {
echo $query.'<br><br>';
die(mysql_error());
}
}
function docreate() {
doquery("drop table if exists mytable");
doquery("create table mytable(column1 integer, column2 integer, column3 integer)");
}
function main() {
$temp3 = array(
array('1','2','3',),
array('4','5','6',),
array('7','8','9',),
);
dologin();
docreate();
doquery("start transaction");
foreach($temp3 as $row)
doquery("insert into mytable values('" . implode("','", $row) . "')");
doquery("commit") or die(mysql_error());
}
main();
?>
Try this :
// lets array
$data_array = array(
array('id'=>1,'name'=>'a'),
array('id'=>2,'name'=>'b'),
array('id'=>3,'name'=>'c'),
array('id'=>4,'name'=>'d'),
array('id'=>5,'name'=>'e')
)
;
$temp_array = array_map('implode', $data_array, array('","' ,'","','","','","','","'));
echo $query = 'insert into TABLENAME (COL1, COL2) values( ("'.implode('"),("', $temp_array).'") )';
mysql_query($query);

help with php FOREACH loop

can some please tell me what's wrong with the bellow foreach php loop.
foreach ($_POST[sortlist] as $key => $value)
{
$sql = "UPDATE sortable
SET color_order = " . mysql_real_escape_string($key) . "
WHERE id = " . mysql_real_escape_string($value);
$result = mysql_query($sql) or die(mysql_error());
}
I keep getting warning: invalid argument suplied foreach() in ....
when i upload to server
Thanks
$_POST['sortlist'] is probably not an array. Try print_r($_POST) to see what do you have there.
Try change $_POST[sortlist] to $_POST['sortlist']
I'm assuming that $_POST[sortlist] is not an array. This is probably what you are trying to do:
foreach ($_POST as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}
Or if $_POST['sortlist'] is an array, try this:
foreach ($_POST['sortlist'] as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}
A tip: the error message refers to the foreach line. That only reads from one variable, $_POST[sortlist], which isn't modified inside the loop. So you can ignore all the SQL stuff; it's not relevant to your problem. Reduce the problem to the smallest possible piece of code that still has an error. That will help you solve it.
Don't use mysql_query , its very insecure and is deprecated .
start using mysqli_query, is not as safe as PDO but will be lot better.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories