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);
Related
I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.
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.")";
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);
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:
<div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:
regid | psc_1 | psc_2 | psc_3 | ...
My code:
if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = #each ($boxes)) {
$camp_string .= "'$camp',";
}
}
// The above to create a comma separated string
$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma
$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.
I'm not sure what I'm missing.
--
Update#1 (in reference to a comment below)
if(!empty($_POST['camps'])) {
$box=$_POST['camps'];
while (list ($key,$val) = #each ($box)) {
$camp_totals += $campcost[$val];
echo "$campdesc[$val] - $$campcost[$val]";
}
}
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:
// print_r($_POST);
array(
'regID' => 1,
'camp_filmore' => 1,
'camp_greenwald' => 1
'camp_idunno' => 1
);
From there it's fairly simple to build your query:
$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
"VALUES (" . implode(array_values($_POST), ", ").")";
You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.
A nice trick to remove the trailing comma would be.
$camp_string = rtrim($camp_string,',');
Anyway your query is not formated correctly.
INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')
You cannot have single quotes in the first bracket
I think you should be looking at implode and you can easily add addition strings to it...
so e.g.
$comma_seperated = implode(',', $boxes);
$subscribed = $regid . ',' . $comma_seperated;
I have a HTML page where a user can select multiple values in a checklist. Depending on the number of items selected, that's how many times I would like to append a variable to itself, separated by commas (if that makes sense)
For example, if my string was $string = "'$apple'" (yes, my string is meant to be formatted this way, you'll see why) and the user selected 3 items from the checklist, my string would end up being:
"'$apple', '$apple', '$apple'"
When the user submits the page, here's the PHP:
$category = mysql_real_escape_string($_POST['category']);
$string = 'test';
if (count($category) === 1) {
//donothing
}
else{
$category = implode(",",$category);
}
$numcat = count($category); //count number of items in $category, save value to $numcat
$query = mysql_query("INSERT INTO table (". $category .") VALUES ('$string')");
For reference, if the user has selected "apple, banana, grape" from the HTML form, I want the query to essentially look like this:
$query = mysql_query("INSERT INTO table (apple, banana, grape) VALUES ('$string', '$string', '$string')");
Another example, if the user has selected just "apple, grape" from the HTML form, I want it to end up looking like this:
$query = mysql_query("INSERT INTO table (apple, grape) VALUES ('$string', '$string')");
The INSERT INTO table (apple, grape) is already solved by just doing INSERT INTO table (". $category .") since I have imploded it and seperated by commas, but then I also need the string to display 'X' amount of times in VALUES, depending on the result from count($category)?
How can I do this?
It looks to me that you want to take a variable and a count and make a string from it. If that is the case, will this work:
$value = "'x'";
$count = 3;
$a = array_fill(0, $count, $value);
$str = implode(',', $a);
Then, $str will contain "'x','x','x'".
You can ask why I didn't use str_repeat. I haven't seen a way to use a glue with that. The implode function lets me use , as the glue. I just needed to make it an array first.