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

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.

Related

PHP array out of order

I am pulling information from a database- from two different tables. The origins of the data is a single archival document- so each row from the two tables has a unique value- line number.
So the code is as follows
//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);
//Time to start building the file to go out.
$total_report = array();
foreach($reports_in_db as $key)
{
$total_report [$key->line_number] = $key;
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
if (empty($abs_sums))
{
//echo "subtitles/abstracts"
}
else
{
foreach ($abs_sums as $key)
{
$total_report [$key->line_number] = $key;
}
}
So what I expected to happen, is to create an array where the main data rows have the subtitles rows interspersed. What actually happens is that $total_report has all the main data rows, followed by all the subtitles rows. When I print_r the array, they're not in the order I expect.
for example, if the data rows are row 1-200, and the subtitle rows are 121, 161, and 181, this code produces an array that has elements 1-120, 122-160, 162-180, then 121,161 and 181 in that order.
Currently, the elements are WPDB objects. If possible, I'd like to be able to just get them in the right order. If there's also a simple way to just sort by the element number, that's okay too.
I've tried doing sort() on $total_report- but that sorted by the alphabetical value of the first field of the object..
I'm honestly just puzzled why the array doesn't have the elements in the order I thought they'd be in.
Thanks
Use ksort() to sort array by keys. And SORT_NUMERIC flag so it would sort it as numbers:
<?php
...
ksort($total_report,SORT_NUMERIC);
...
?>

passing multidimensional array to mysql using generated input fields

<?php
if (isset ($_POST['submit'])){
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
$query="INSERT INTO athletes (name, sports) VALUES ('".$data."')";
$result = mysqli_query($dbc, $query);
mysqli_free_result( $result);
}
?>
getting error array to string conversion.
hot do i pass that in the database in separate rows.
the output is working wonderfully when i dump just the way i want it but i cant seem to get it passed to the database.
I think you don't need to make multidimensional array name[][], you just use name[] so in your PHP code it is just like,
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
Demo
You can change $data while inserting in database like,
$data[]='("'.trim($nm).'","'.trim($sports[$x]).'")';
And after your loop ends you can create query like,
$sql ="INSERT INTO <table> (name,sports) VALUES ".implode(',',$data);
Demo with Query
You need to create separate array from post value for each row.
http://sandbox.onlinephpfunctions.com/code/c8aede27dc5675a8715be328dec6c5ea4c669522

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

Assigning PHP Variable to MySQL Array

I know there is a simple answer but I can't seem to put this together. I am successfully pulling an array from a MySQL table in the following code, but I would like to assign individual PHP variables to each item.
<?php
$con = mysql_connect("$hostname","$username","$password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("$database", $con);
$result = mysql_query("SELECT * FROM table WHERE state=1");
while($row = mysql_fetch_array($result))
{
$value=$row['id'];
}
mysql_close($con);
?>
When I run this loop I get the output of the id's as 1,2,3,4,5,6,7. How can I go about assigning individual PHP variables to each of these values?
You can put the variables in an array.
$values[] = $row['id'];
and then reference it as $value[0], $value[1] ...
Also take a look at list which allows you to assign individual variables as if they were an array.

Unable to insert value in db when inside foreach() and for()

When a form is posted it is passed on as a value1,value2,value3, value4. It has been exploded as individual values.
Everything works well except for when I am trying to insert the value1,value2,value3 into $variable[$i] it is not inserted into the table. But when echo $variable[$i]; it works fine.
Any idea on why the values are not inserted into the db.
foreach ($_POST['ECB'] as $lx) {
for($i=0;$i<=$Count;$i++) {
$k += mysql_num_rows($el);
echo $variable[$i];
mysql_select_db($database_m, $m);
$query_stat = "Insert into table (field) values ('$variable[$i]')";
$Result = mysql_query($query_stat, $m) or die(mysql_error());
}
}
If the type of the field in the database is some kind of numeric types (INT, DECIMAL, FLOAT etc) then you must remove the single quotes from your SQL query. It should look like the one shown below.
$query_stat = "Insert into table (field) values (".$variable[$i].")";

Categories