Multiple records inserting into MySql from PHP form - php

I think I've got a tiny mistake in my code so when I try to add two records to MySQL database it adds them both, but at the moment its only adding the second row that should be inputted. SO for example I have two RefTitle fields, two RefSurname fields and so on!
Some PHP Code:
<?php
if(empty($err)) {
for($i = 0; $i < 2; $i++)
{
$RefTitle = $_POST['RefTitle'][$i];
$RefSurname = $_POST['RefSurname'][$i];
$RefForenames = $_POST['RefForenames'][$i];
$RefInstitute = $_POST['RefInstitute'][$i];
$RefEmail = $_POST['RefEmail'][$i];
$RefTelephone = $_POST['RefTelephone'][$i];
$EmailOK = $_POST['EmailOK'][$i];
$sql_insert = "INSERT into `referees`
(`RefTitle`,`RefSurname`,`RefForenames`,`RefInstitute`, `RefEmail`,
`RefTelephone`,`EmailOK`)
VALUES
('$RefTitle','$RefSurname','$RefForenames','$RefInstitute','$RefEmail',
'$RefTelephone','$EmailOK'
)
"; ?>
I have the [] after each name field in my html form.
Thanks

Here's what I think is happening.
In the loop, you're adding the current query to a string, overwriting the previous query. After the loop ends, you run mysql_query but this will only run on the last query generated by the loop.
You have two ways to fix this:
Execute the query within the loop on every iteration. Pseudo code:
for ($i = 1 to 100)
{
$query = //build your query;
mysql_query($query);
}
Alternatively, (and the better way) is to use a value list in your insert statement.
An insert with a list of values looks like this
INSERT INTO table VALUES (1,2,3), (4,5,6), (7,8,9)
So, (pseudo code again)
$query = "INSERT INTO table VALUES ";
for ($i = 1 to 100)
{
$query .= " (";
$query .= "" //comma seperate the values of the current iteration
$query .= "),";
}
//after loop ends, remove the trailing extraneous comma
// execute the entire query at once
mysql_query($query);

Related

Inserting multiple rows from php foreach

I have an html form with dynamic (user-determined) number of rows, each with several inputs; I'm trying to achieve a MySQL query which will insert rows
into the db table, more or less row-for-row (although there is a value $_POSTing from outside this table which I will also add to the INSERT).
I'm retrieving these values like this:
<?php
if (isset($_POST['submit'])) {
$lineItems = array();
foreach ($_POST['date'] as $i => $value) {
$customer = $_POST['customer'][$i]; // this value is from *outside* the line items table
$date = $_POST['date'][$i];
$time = $_POST['time'][$i];
$fee = $_POST['fee'][$i];
$lineItems[] = "('$customer', '$date', '$time', '$fee')";
// I realize the query should be outside the loop, but what I'm trying to do is something like this (pseudo-code):
$query = "INSERT INTO Line_Items (CUSTOMER, DATE, TIME, FEE) VALUES ". implode(", ", $lineItems)
. "ON DUPLICATE KEY UPDATE
CUSTOMER = VALUES(CUSTOMER),
DATE = VALUES(DATE),
TIME = VALUES(TIME),
FEE = VALUES(FEE)
";
}
}
?>
With this query - inside or outside the loop - I'm only inserting values from the last row of inputs; can someone please explain with an example how
to construct a query to insert multiple line items and the appropriate query? Thank you so much.
Inside the loop you will get a row for each line in the post - outside the loop you will only insert the last row.
If you just need the last row - then there is no need to loop over the entire set to get to it.
You could count the rows - and then target the last row directly - see php
count()
Change line
$lineItems[] = "('$customer', '$date', '$time', '$fee')";
to
$lineItems[] = "(".$customer.",".$date.",".$time.",".$fee.")";

PHP HTML checkbox only submitting last value MySQL issue

I have a group chat feature on my site and people can add friends by selecting HTML checkboxes, so multiple can be added at one point. However, when my PHP script inserts the data into the MySQL database, only the last value is added. For example, if the user selects 3 friends, PHP separates their ID's by commas (as it will be stored as an array in the database); so it would display like ,1,2,3. However, when I insert into MySQL, only the ",3" is submitting.
PHP code to assemble data from HTML checkbox:
$invite = $_POST['invite'];
if(empty($invite))
{
//echo("You didn't select any friends.");
}
else
{
$N = count($invite);
//echo("You selected $N friends(s): ");
for($i=0; $i < $N; $i++)
{
$userinput = ("," . $invite[$i]);
}
}
MySQL query:
$sql = "INSERT INTO group_chat (title, created_date, last_modified, created_by, user_array) VALUES ('$title', now(), now(), '$logOptions_id', '$logOptions_id$userinput')";
$logOptions_id contains the ID of the current user.
I've echoed the $userinput variable out before and it appears as it should be: ,1,2,3 (comma at the start seperates from current user ID when adding to MySQL.
You are overwriting the values in the loop with this line
$userinput = ("," . $invite[$i]);
Change it to this
$userinput .= ("," . $invite[$i]);
Remember to initialize the the variable $userinput before appending to it to avoid undefined variable warning.
you can create the comma separated id string using implode
$userinput = implode(',', $invite); // output as 1,2,3
If you want to add current user id to it
$userinput = $logOptions_id.','.implode(',', $invite);

Loop MySQL-Query 10 times for each item in array (PHP & MySQL)

I'm trying to write a Top-10 list with categories but it doesn't work in the way i want it to. There's an array with a dynamic number (n) of items and want to loop each item in this array 10 times to write n*10 rows into a MySQL table. ($i also increments the games rank).
If I echo, print_r or var_dump the code it works, but when I try to write it to the MySQL table it doesn't work.
Here's the code:
for ($i = 1; $i <= 10; $i++) {
foreach($titles as $val) {
$query .= "INSERT INTO charts (game_place, game_name, game_preweek, game_developer, game_release, game_link, game_image, game_category, charts_updated) VALUES (".$i.", '', '', '', '', '', '', '".$val."', '".time()."');";
mysql_query($query);
};
};
Does somebody know the answer to my problem?
$query .= "INSERT ....`
You're adding each new query onto the end of the previous query. That's going to produce invalid SQL after the first iteration. You just need to assign the query as:
$query = "INSERT ....`
You should also look at using PDO or mysqli_ instead - this sort of thing is an ideal use for a prepared statement.
$query = "INSERT INTO `charts`` (`game_place`, `game_category`, `charts_updated`) VALUES ";
foreach ($titles as $key => $val){
for ($i=1; $i<=10; $i++){
$query .= "(".$i.", '".$val."', ".time()."),";
}
}
$query = substr($query, 0, -1);//remove last comma
mysql_query($query);

SQL Query not completing correctly - not sure why

Alright,
I've got a multiple select dropdown on a page called week-select, its selections get passed via ajax to my php page.
I can get the data just fine, but when the query runs it doesn't complete appropriately.
I've got this:
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
If I just select one week it works great and displays the appropriate data.
If I select multiple options (say weeks 12, 14 and 15) it runs the query but only displays week 12.
When I manually input the query in SQL, how I imagine this query is getting entered - it runs and displays the appropriate data. So if I put SELECT * FROM mytablename WHERE WK IN ( 12, 14, 15 ) it gets exactly what I want.
I can't figure out why my query isn't executing properly here.
Any ideas?
**EDIT: I make the array from the multiple selections a string using javascript on the front end before it is passed to the backend.
Your resulting query with values probably looks like this with a single value in IN:
… WK IN ("12,14,15") …
Either use one placeholder for each atomic value:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
Or use FIND_IN_SET instead of IN:
$sql[] = " FIND_IN_SET(WK, ?) ";
I don't think you can bind an array to a singular ? placeholder. Usually you have to put in as many ? values as there are elements in your array.
If your HTML is correct and your week select has name="week[]", then you will get an array back with $_GET['week'];, otherwise without the [] it will only give you 1 value. Then, you're doing a string replace, but it's not a string. Instead, try this:
$weekFilter = implode(',', $_GET['week']);

MySQL INSERT - Using a for() loop with query & do non-set values insert as "" by default?

I have two arrays with anywhere from 1 to 5 set values. I want to insert these values into a table with two columns.
Here's my current query, given to me in another SO question:
INSERT INTO table_name (country, redirect)
VALUES ('$country[1]', '$redirect[1]'),
('$country[2]', '$redirect[2]'),
('$country[3]', '$redirect[3]'),
('$country[4]', '$redirect[4]'),
('$country[5]', '$redirect[5]')
ON DUPLICATE KEY UPDATE redirect=VALUES(redirect)
I'm a little concerned however with what happens if some of these array values aren't set, as I believe the above assumes there's 5 sets of values (10 values in total), which definitely isn't certain. If a value is null/0 does it automatically skip it?
Would something like this work better, would it be a lot more taxing on resources?
for($i = 0, $size = $sizeof($country); $i <= size; $i++) {
$query = "INSERT INTO table_name (country, redirect) VALUES ('$country[$i]', '$redirect[$i]) ON DUPLICATE KEY UPDATE redirect='$redirect[$i]'";
$result = mysql_query($query);
}
Questions highlighted in bold ;). Any answers would be very much appreciated :) :)!!
Do something like this:
$vals = array()
foreach($country as $key => $country_val) {
if (empty($country_val) || empty($redirect[$key])) {
continue;
}
$vals[] = "('" . mysql_real_escape_string($country_val) . "','" . mysql_real_escape_string($redirect[$key]) . "')";
}
$val_string = implode(',', $vals);
$sql = "INSERT INTO .... VALUES $val_string";
That'll built up the values section dynamically, skipping any that aren't set. Note, however, that there is a length limit to mysql query strings, set by the max_allowed_packet setting. If you're building a "huge" query, you'll have to split it into multiple smaller ones if it exceeds this limit.
If you are asking whether php will automatically skip inserting your values into the query if it is null or 0, the answer is no. Why dont you loop through the countries, if they have a matching redirect then include that portion of the insert statement.. something like this: (not tested, just showing an example). It's one query, all values. You can also incorporate some checking or default to null if they do not exist.
$query = "INSERT INTO table_name (country, redirect) VALUES ";
for($i = 0, $size = $sizeof($country); $i <= size; $i++) {
if(array_key_exists($i, $country && array_key_exists($i, $redirect)
if($i + 1 != $size){
$query .= "('".$country[$i]."', '".$redirect[$i]).",";
} else $query .= "('".$country[$i]."', '".$redirect[$i].")";
}
}
$query .= " ON DUPLICATE KEY UPDATE redirect=VALUES(redirect);"
$result = mysql_query($query);

Categories