PHP - Upload data to database using a loop - php

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 />";
}

Related

Insert array to to single MySQL raw with foreach

I need to insert MySQL data from array values to a single raw. I have tried code below but I am getting error: Warning: implode(): Invalid arguments passed in
How can I solve this problem? Or is there any alternative way to insert array values to single raw in MySQL using PHP?
<?php
foreach ($_POST['qty'] as $product_id => $qty) {
$product_id = implode(" ",$product_id);
$qty = implode(" ",$qty);
}
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id','$qty')");
?>
Implode function second parameters accept Array so at first check in implode function the second parameter is array.
foreach ($_POST['qty'] as $product_id => $qty)
This line says $product_id is key which is not array so implode function should not work.
Please provide $_POST['qty'] dump
Try this:
<?php
$product = [];
$qtys = [];
if(!empty($_POST['qty'])){
foreach ($_POST['qty'] as $product_id => $qty) {
array_push($product, $product_id);
array_push($qtys, $qty);
}
$qty_final = implode(',',$qtys);
$product_id_final = implode(',',$product);
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id_final','$qty_final')");
}
It is very bad idea to save comma separated values in db.
This is not a good idea. - It is a very bad idea.
That being said. Your $product_id is not an array - it is an array key (string or integer) so there is nothing to implode.
Instead of inserting csv into this table it would be a much better idea to insert new row for each id you have.
try this :
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
If you want to post array to database then use php serialize function.It is best for array type data
$serialized_data = serialize(array('Math', 'Language', 'Science'));
echo $serialized_data . '<br>';
You could do,
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
This should work.
But keeping comma seperated list in a field is not a good thing to do. You could have a new table, so that you can keep a mapping to what products are in what order.

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);

implode() array to insert record into mySql database

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);

passing dynamic multidimensional array from jQuery to php and insert into database

Hi I am trying to post dynamic arrays from jQuery to PHP to mysql
I get the data from jQuery and able to serialize the data
php takes the variable and it comes up as and array
but when I try to pass the variables for my insert and depending where I put it in the foreach() I either get only the last of the arrays inserted to the database or
multiple inserts of everything (ie: name1, prob1, date1 name1, prob1, date2 ect ect..).
$name, $problem, $timedate post as arrays from jQuery.
in this example I only get the last one of the array
<?php
$name = $_POST['name'];
$problem = $_POST['problem'];
$timedate = $_POST['timedate'];
$con = mysql_connect("localhost","wayko","b4v0e1jj");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("joinus", $con);
$seriname = mysql_real_escape_string(serialize($name));
$seriprob = mysql_real_escape_string(serialize($problem));
$seritd = mysql_real_escape_string(serialize($timedate));
foreach($name as $valname){
foreach($problem as $valprob){
foreach($timedate as $valtd){
}
}
}
$sql="INSERT INTO roomchart (Name,TimeDate,Problem)
VALUES
('$valname','$valtd','$valprob')";
echo $sql;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error(). "Actual query: " . $sql);
}
mysql_close($con);
?>
In this example I get multiple inserts of the same data so 3 inserts become 9
foreach($name as $valname){
foreach($problem as $valprob){
foreach($timedate as $valtd){
$sql="INSERT INTO roomchart (Name,TimeDate,Problem)
VALUES
('$valname','$valtd','$valprob')";
echo $sql;
}
}
}
any ideas?
That's how foreach works. In your first example, your three nested foreach loops have nothing in them, so PHP just loops to the last element of each of those three arrays. Then, when you do your SQL statement, you're only doing it once - with the last element of each of those three arrays.
For your second example, you're taking each element of $name, matching it with each element of $problem, and matching each of those combinations with each element in $timedate. So assuming you have 3 elements in each array, you've made 3x3x3 = 27 different combinations of elements from those three arrays (and then SQLing each of those combinations into your database).
I'm assuming that you have 3 arrays of equal size, and you want to pair $name[0] with $problem[0] with $timedate[0], $name[1] with $problem[1] with $timedate[1], etc. Assuming your arrays just have autoincrementing keys (like in the previous sentence), you can use:
foreach ($name as $key => $valname) {
$sql = "INSERT INTO roomchart (Name, TimeDate, Problem)
VALUES ('$valname', '$timedate[$key]', '$problem[$key]')";
echo $sql;
}
This will give you the proper pairing you want.
EDIT EDIT: The last EDIT doesn't work. Use the previous code.

Categories