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;
Related
I want to break comma seperated values which are retrieved from database and then put each individual in a string and print it in a for loop only. I am getting the values from database but i am not be able to break values. Below is the code what i have done right till now.Please help to solve my issue. Thanks in advance.
$query="select * from create_segment";
$result = mysql_query($query,$link) or die(mysql_error());
$number_of_segment=mysql_num_rows($result);
while($row=mysql_fetch_assoc($result))
{
$segments[]=$row;
}
foreach($segments as $success) {
$thePostIdArray = explode(', ', $success['subjects']);
for($i=0; $i < count($thePostIdArray); $i++)
{
echo "string...".$strings=$thePostIdArray[$i];
}
}
It output:
string...1,2,3,4,5,6,7,8,9,10
string...1,2,3,4,5,6,7,8
but i want something like this:
for(......)
{
echo "values...".$i;
}
which should output
values...1
values...2
values...3 and so on.
my database structure is like:
id subjects
1 1,2,3,4,5
2 1,2,7
Please try to use ',' instead of ', ' in your
explode(', ', $success['subjects']);
statement so it would look like:
explode(',', $success['subjects']);
Use:
explode(',', $success['subjects'])
You had a space after the comma, but there are no spaces in the database values.
If you have the opportunity to change the database structure you should convert that table into something like this:
Id Subject
1 1
1 2
1 3
2 1
etc.
It will make your queries much easier, and it the right way to go. It will also make it easier for you in the future do join this table with other tables to get the desired results. I know this doesn't answer your questions, but some good advice will never hurt. One of the other answers will answer your question directly.
$query="select * from create_segment";
$result = mysql_query($query,$link) or die(mysql_error());
$number_of_segment=mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
foreach (explode(',',$row['subjects']) as $value){
echo echo "string... {$row['id']} " . $value . '<br />';
}
}
I'm new to PHP. I'm trying to split up my array (done successfully) and submit them as individual submisions into my MYSQL Table (via FOR loops). However, using the code below, it only submits the LAST object in the array. And thus defeats the whole purpose of the desired function. Can anybody show me a way to avoid this?
$directives = "(John Doe, Directive, Time)(Jane Doe, Directive2, Time2)";
$action = explode("(" ,str_replace (")","",$directives));
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$sqlaction="INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES
('$namesplit[0]','$namesplit[1]',' Directive','$actiondo','$date')";
}
You are overwriting your query in $sqlaction with each loop iteration, thus this is not useful.
You also don't need a query for each row. You can build up a query that would allow insert of all rows with a single query. Something like this:
$query = 'INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES ';
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$query .= "('" . $namesplit[0] . "','" . $namesplit[1] . "'Directive','" . $actiondo . "','" . $date . "'),";
}
$query = rtrim(',', $query);
// not shown - execute query using $query
First, you would have to put the code that actually puts stuff in the database inside the loop in order to do lots of individual submissions. All your code currently does is just set the same string over and over. That's why only the last one gets inserted.
Second, why don't you just do one insert? You can have multiple values parentheses, you know. Like this:
VALUES (x, y, z), (x2, y2, z2), (x3, y3, z3)
Third, your design is just asking for trouble because you're making so many assumptions about your data. Imagine that there's a person like "James Earl Jones" in your list. Here's how it would go:
$namesplit = explode(" ", 'James Earl Jones');
echo $namesplit[0]; // = James
echo $namesplit[1]; // = Earl
Oops, now his name is just "James Earl."
To avoid this kind of thing, you have to check the data carefully before inserting it, and you really need to think about what might happen if there are extra commas or spaces every time you do those explodes.
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);
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']);
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.