implode() array to insert record into mySql database - php

I have a single row in a PHP array and I would like to insert that row into mySQL database by imploding the keys and values into a string and using those strings in my Insert statement as follows:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", $_POST);
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ('$newdata')");
$result = mysqli_query($dbc, $query);
I am able to create the strings, and they appear to be in proper form ,however the row is not being inserted. Seems like a simple approach but not sure what I'm missing.

As #Barmar has pointed out, the problem is your quotes are on the outside of your variable.
I think this may be an easier to follow/cleaner way of fixing this however than the method Barmar posted:
$newdata = "'" . implode("','", $_POST) . "'";

You need to quote each value, not the entire list of values:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", array_map(function($x) use ($dbc) {
return "'" . $dbc->real_escape_string($x) . "'";
}, $_POST));
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ($newdata)");
$result = mysqli_query($dbc, $query);

Related

Putting a JSON result within []

I am trying to add values from a JSON API to a MySQL. The problem is that the result return without the [], so I cannot foreach it and insert all the values to the database.
This is the API URL
http://horoscope-api.herokuapp.com/horoscope/today/Gemini
This is the code I am having
$data = file_get_contents(
"https://horoscope-api.herokuapp.com/horoscope/today/Gemini",
true);
$array = json_decode($data, true); //Convert JSON String into PHP Array
foreach($array as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO zodiac(date, horoscope, sunsign, url)
VALUES (
'" . $row["date"]. "',
'" . $row["horoscope"]."',
'" . $row["sunsign"]."',
'" . $row["sunsign"]."'
); "; // Make Multiple Insert Query
}
If I combine $data = "[$data]"; (with and without the quotes) it prints correctly but cannot be parsed as an array. Or at least I cont know how to do it.
I have tried searching for some way to fix that and found some interesting ideas here How to convert JSON string to array but none of them seems to work.
And other way to get the result within []?
Thanks
If I don't misunderstood you requirements then this should work for you. I've seen the API response, it is just returning a single result for a horoscope. Though I've just used your existing code to make it workable(which is not recommended to use), I wish you'll try with PDO instead.
<?php
$data = file_get_contents("https://horoscope-api.herokuapp.com/horoscope/today/Gemini",true);
$array[] = json_decode($data, true); //Convert JSON String into PHP Array
$query = '';
foreach($array as $key=>$row) //Extract the Array Values by using Foreach Loop
{
$query.= "INSERT INTO zodiac(date,horoscope,sunsign,url)
VALUES ('". $row["date"]."','".$row["horoscope"]."','".$row["sunsign"]."','".$row["sunsign"]."'); "; // Make Multiple Insert Query
}
echo $query;
?>
With PDO:
$data = file_get_contents("https://horoscope-api.herokuapp.com/horoscope/today/Gemini",true);
$array = json_decode($data, true); //Convert JSON String into PHP Array
$sql = "INSERT INTO zodiac (date, horoscope, sunsign) VALUES (:date, :horoscope, :sunsign)";
$stmt= $dpo->prepare($sql);
$stmt->execute($array);

MySQL Insert error with null values

So i'm trying to insert data into a MySQL table from an array that contains multiple arrays which hold data for each row of a table using the code below:
if (is_array($tbl_data)){
$sql = "INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values ";
$arrayValues = array();
foreach ($tbl_data as $row){
$agent = mysql_real_escape_string($row[0]);
$event = mysql_real_escape_string($row[1]);
$data1 = mysql_real_escape_string($row[2]);
$data2 = mysql_real_escape_string($row[3]);
$data3 = mysql_real_escape_string($row[4]);
$data4 = mysql_real_escape_string($row[5]);
$data5 = mysql_real_escape_string($row[6]);
$value = "($agent,$event,$data1,$data2,$data3,$data4,$data5)";
array_push($arrayValues, $value);
}
$sql .=implode(',', $arrayValues);
Quick check using var_dum($sql) produces the following:
INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,,,,,)/////
The above Sql is invalid due to the multiple commas here :(NONE,QUEUESTART,,,,,)which are generated by empty fields. How can I insert single quotations inside the query to make it valid ? i.e the correct sql syntax:
INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,'','','','','')
Either:
$data1 = "'" . mysql_real_escape_string($foo) . "'";
or
$value = "(...,'$data1',...)";
Just don't try both options, which would give you (...,''$data1'',...) and kill the query with syntax errors.

Creating an INSERT statement for all $_POST variables in an array

We are all familiar with traditional form processing i.e.
$email = $_POST['email']; $name = $_POST['name'];
etc.. and then we go ahead and get all the variables from a post.
and then we would create a compound statement like
$qry = "INSERT INTO $tableName (email,name) values ('$email','$name')";
Now what if you had like 18-20 questions? most people would just write lines and lines of code 99.9% of everyone online does it the same way over and over again.
Let's try something different shall we?
I realized there must be a better way using arrays.
For years I've been looking for a simple routine and looked everywhere for it that will CRAFT an insert statement FROM all the $_POST variables.
It dawned on me that $_POST is actually an array so I wrote this little script:
$vars = $_POST;
print_r($vars);
exit;
After working thru this for a few hours with people on this forum here is the resulting code. I believe that by creating a checksum of the hash of all the array keys will solve the fears of SQL attacks, since the server isn't called unless it gets an exact match. If anyone adds a field it will fail. Does everyone agree?
$predefinedChecksum = "84e602bbec8124f298e353171fb7f5b2"; // this is the hash value of all the array keys
$keys = array_keys($_POST);
$values = array_values($_POST);
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ('" . join("',", $values) . "');";
$checksum = md5(join(',',$keys));
if ($checksum<>$predefinedChecksum) exit;
else $res = mysql_query($qry, $conn);
Thanks to all who contributed... I think we've got the workings of a great script.
Someone mentioned to unset the 'button' - how do you do that?
unset( $_POST['button'] );
This did not work - the output of the script still shows 'button' as one of the variables. So the output of the script still has a field called 'button' in the end.
I'm not sure how you could remove it from the series of $values
Anyone have ideas?
Also the output
INSERT INTO (nameFirst,nameLast,emailPref,emailAlt,phoneDay,phoneMobile,ethnicity,yob,income,marital,kids<18,Education,employment,company,title,industry,department,revAnnual,numemps,street,city,state,zip,Type_Mobile,tablet,computer,laptop) VALUES ('Vik',Grant',viktor#eml.cc',',',',african',',19',single',',Some_HS',student',',',Finance_Accntg',Admin',',',',',',',Android',',',');
is missing the ' quote mark on the beginning of the value - can a join exist as join (a,b,c)?
Just loop it with foreach http://nl1.php.net/manual/en/control-structures.foreach.php be careful as this allows any column to be overwritten.
It is safer to specify which columns are allowed to be inserted.
And plz use something like PDO to use prepared statements
You don't really want to do this since you generate queries which can be altered by the client.
But to answer your question, you can do something like:
$columns = array("email", "name", "etc.."); // Array with the "good" columns.
// Unset the columns you do not want in your query.
foreach($_POST as $key=>$value){
if(!in_array($key, $columns)){
unset($_POST[$key]);
}
}
$qry = "INSERT INTO " . $tableName . " (" . implode(", ", array_keys($_POST)) . ") values (" . implode("', '", array_values($_POST)) . ")";
Although the normal way is to use a loop for producing the string containing your values, i sometimes do the following when i know the exact order of keys in my array:
$arr = array(
"email"=>"foo#bar.gr",
"name"=>"vlzvl"
);
$sql = "INSERT INTO mytable (email,name) VALUES ('".implode("','",$arr)."')";
you shouldn't do this since its huge security issue.
But if you really want to do this: (untested, you can still inject SQL so this ain't secure!)
$keys = array_keys($_POST);
$values = array_values($_POST);
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ('" . join("',", $values) . "');";
Edit:
If you are using PDO, you could do it like this:
$keys = array_keys($_POST);
$values = array_values($_POST);
$valuePlaceholders = "";
for ($i=0; $i < count($_POST); $i++) {
$valuePlaceholders .= $i === 0 ? '?' : ', ?';
}
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ($valuePlaceholders);";
And when executing $pdo->execute($values);

Php function to run mysql queries

I am trying to create functions to run mysql queries
How would I do things like insert queries. I was thinking
function insert_query ($table,$cols,$values)
{
$sql="insert into $table ($cols) values ($values) "; ...etc
}
With the rest of the query code in the function. But how would I add multiple columns and values?
Should I make $cols and $values An array inside the function?
This is a function of my Database Class.
public function insert($table,$values){
$fieldNames = "";
$fieldValues = "";
foreach($values as $key => $value){
$fieldNames .= "$key,";
$fieldValues .= "$value,";
}
$fieldNames = substr($fieldNames,0,-1);
$fieldValues = substr($fieldValues,0,-1);
$sql = "INSERT INTO $table($fieldNames) VALUES ($fieldValues)";
$this->newConnection();
$result = $this->mysqli->query($sql);
$this->closeConnection();
return $result;
}
Here is what I'm using. Pass field name and Value as Array key and value. $lsQry is an array of field name & value pair
function insert_record($table,$lsQry)
{
$fields_str = implode(',',array_keys($lsQry));
$data_str = implode("','",$lsQry);
$data_str = "'" . implode("','", $lsQry) . "'";
$lsQry = "INSERT INTO $table($fields_str) VALUES($data_str)";
$rs = mysql_query($lsQry);
if(isset($rs))
return true;
else
return false;
}
Please Note
For this function, do consider that function is getting an array of fields name and value pair. It is assumed that htmlentities() and addslashes() or any escaping functions are already applied while creating array from post/get values.
Easy, just us arrays
function insert_query ($table,$cols,$values){
$sql="insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
insert_query('exampleTable', array('column_1', 'column_2', 'column_3'), array('a', 123, 'c') );
The implode for the values requires a small sidenote:
Strings always required being wrapped in quotes. Therefor I made the implode with single qoutes. The downside to this is that integets (like 123 in the example) also get wrapped.
This is not a big problem, but if you want you could replace the implode with a foreach that uses is_numeric to check wether it should be wrapped in quotes.
IMPORTANT SECURITY NOTE:
In this example I havent used proper seurity, like escape_string(), this has to be added! I've not added thos to keep the examples smaller
Another approach could be key/value-usage of an array:
function insert_query ($table,$data){
$cols = array_keys($data);
$values = array_values($data);
$sql = "insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
$info = array('column_1'=>'a', 'column_2'=>123, 'column_3'=>'c');
$info['example'] = 'Easy method to add more key/values';
insert_query('tableName', $info);
In this case you can use functions similar to codeigniter functions.
Use arrays to store table name and columns or values
For example:
$data = array('hid' => $hcsdate,'start_date' => $sdate, 'end_date' => $edate, 'title' =>$title);
Here $data holds the column name and corresponding values.
And pass this $data to another functions for insert, update etc..

PHP - Upload data to database using a loop

I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array.
As such:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
}
var_dump($selected);
The above code is working and when I open it in my browser I get this output
Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:
foreach ($selected as $player){
$sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")')
or die(mysql_error());
print ($player);
echo'<br>';
` }
Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows:
If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.
Thanks in advance.
You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.
use this:
'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'
instead of this:
'INSERT INTO `team`(`player_name`) VALUES ("$player")'
Just replace following code with your ones code and it will work efficiently.
foreach ($selected as $player){
$sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')")
or die(mysql_error());
echo "$player<br />";
}

Categories