SQL loop with $i and $_POST Values - php

I am trying to loop through a number of results from a form, but can't get it quite right.
for ($i=1;$i<$total;i++)
{
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
}
I want $_POST['$iH'] to be the same as $_POST['1H'],$_POST['2H'], $_POST['3H'] etc.

Like so:
for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
$sql = "INSERT INTO MYSQL(value1,value2,value3) ";
$sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
mysql_query($sql);
}
But, two big problems.
Multiple queries
Boy, what a waste! Dispatch one instead:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
SQL injection
It continues to baffle me how, in 2011, people are still not getting this.
If you're going to insist upon using the ancient mysql API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}'," .
"'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
"'" . mysql_escape_string($_POST[$i . 'A']) . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.

You really need to escape your post variables with mysql_real_escape_string()... you are seriously looking for trouble like that.
In answer to your question, I think you need to do something like this:
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}', '" . $_POST[$i . 'H'] . "', '" . $_POST[$i.'A']. "'");
with the letters rubbing up against your variable, the php engine will assume they are part of the variable name; that variable name does not exist, so you will get some strange results.

You need to escape your quotes because your variable is being passed as a literal:
for ($i=1; $i<$total; $i++)
{
mysql_query('INSERT INTO MYSQL(value1,value2,value3) VALUES("' . $i . '","' . $_POST[$i . 'H'] . '", "' . $_POST[$i . 'A'] . '")');
}

Related

How to save different Json data to same database table of Mysql using Php

I'm trying to save some json data that gets generated randomly . It can have 6 keys or just 3 keys as shown below.
Array sample:
sample 1:
{
"report": {
"a-key": "a-value",
"b-key": "b-value",
"c-key": "c-value",
"d-key": "d-value",
"e-key": "e-value",
"f-key": "f-value",
}
}
Sample 2:
{
"report": {
"a-key": "a-value",
"c-key": "c-value",
"f-key": "f-value",
}
}
Database Table name : plogs
columns: id,logdate, logtime, a, b, c, d, e,
id is unique key that auto increments
Below is the Php code i tried to use. I was able to successfully generate a text file for each json input without any errors.however I'm not able to save the values to the database. Can you please let me know where im making a mistake.
P.S Part of the code i got it off some tutorials
<?php
// Send `204 No Content` status code.
http_response_code(204);
// Get the raw POST data.
$data = file_get_contents('php://input');
$newfilename = date('Y-m-d-H-i-s') . ".txt";
file_put_contents($newfilename, $data);
// a new json file with one of the 2 sample arrays
$date1 = date('Y-m-d');
$time1 = date('H:i:s');
$b = NULL;
$d = NULL;
$f = NULL;
$connect = mysqli_connect("localhost", "dbuser", "dbpassword", "dbname") or die ("error"); //Connect PHP to MySQL Database
$query = '';
$array = json_decode($data, true); //Convert JSON String into PHP Array
function array_keys_exist(array $array, $keys)
{
$count = 0;
if (!is_array($keys)) {
$keys = func_get_args();
array_shift($keys);
}
foreach ($keys as $key) {
if (isset($array[$key]) || array_key_exists($key, $array)) {
$count++;
}
}
return count($keys) === $count;
}
foreach ($array as $row) //Extract the Array Values by using Foreach Loop
{
if (array_keys_exist($array, 'b-key', 'd-key', 'f-key'))
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $row["b-key"] . "', '" . $row["c-key"] . "', '" . $row["d-key"] . "', '" . $row["e-key"] . "', '" . $row["f-key"] . "' ); ";
} else
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $s1 . "', '" . $row["c-key"] . "', '" . $s2 . "', '" . $row["e-key"] . "', '" . $s1 . "'); ";
}
}
mysqli_multi_query($connect, $query);
mysqli_close($connect);
in the code of the foreach loop you are checking if the array keys are in the array variable, you should check in the $row variable as in:
if (array_keys_exist($row, 'b-key', 'd-key', 'f-key')) {
SIDE NOTE: remember to sanitize strings if they come from users, otherwise your code will be unsecure.
EDIT: for real security, as Dharman pointed out in comments, the proper way to proceed is to use prepared statements with parameter binding.
cheers

Using Semaphores in PHP

I'm having this problem where my database entries are not writing to my table in the correct order. I figured it was because they were entering asynchronously. Therefore, I tried to put them in a function that would synchronize the queries. I came up with the following:
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$semRes = sem_get(123321, 1, 0666, 1);
if(sem_acquire($semRes))
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
sem_release($semRes);
}
}
When I don't use semaphores and have only the query in my function
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
}
then the funcion works but the I'm back to the problem of the entries entering in the wrong order. When I add the semaphores, the entries don't enter my table and my console gives me the error "GET ... 500 (Internal Sever Error)". Am I using the semaphores incorrectly or is there something I'm missing. Any help would be appreciated. Thanks.

PHP script slow on server, but fast in local

First I want to say that my english is very poor, but I'm going to try.
I've tried to run a PHP script on my PC with wamp server and it works ok, but when I upload, for some reason, it spends so much time to complete the execution on the host, and almost always ends with a Service Temporarily Unavailable error (the host close the connection).
I've used some die() to see where is the problem and I found it's a for loop where I'm making a big string (I'm only concatenating to make a big INSERT for executing it after the loop). And this loop works in local... I can't understand why is not working on the host.
//insertar valores en bbdd
$sql = "Insert into valor values ";
$primer = 1;
$tiempo_inicio = microtime(true);
for($i = 0 ; $i <= count($array2) - 1 ; $i++)
{
//insertar glucosa
if(!$array2[$i][1] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Glucosa', " . $array2[$i][1] . ")";
$this->Comprobar_Aumentar_Avisos($array2[$i][0], $array2[$i][1]);
}
//insertar raciones
if(!$array2[$i][2] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Raciones', " . $array2[$i][2] . ")";
}
//insertar insulina
if(!$array2[$i][3] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Insulina', " . $array2[$i][3] . ")";
}
}
$tiempo_total = microtime(true) - $tiempo_inicio;
die($tiempo_total);
if ($sql != "Insert into valor values ") {
$AccessBD = new TAccessBD;
$AccessBD->usuario = $this->paciente;
$AccessBD->Inicialitzar_BD();
$AccessBD->query = $sql;
$res = $AccessBD->Ejecutar_SQL();
$AccessBD->Finalitzar_BD();
unset($AccessBD);
}
The problem was that in the loop I was accessing too many times the database in this function: $this->Comprobar_Aumentar_Avisos($array2[$i][0], $array2[$i][1]);
When accessing in local I have no problem, because of local database, but on the server, with the database in other external host too, it was very slow.
So I solved it reducing the number of accesses to database to the minimum I can and now it's working fine.
Thank you very much for the help!

How to write query for a php array?

I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");

how to assign and concat using multiple delimiters in an array?

i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.

Categories