This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}
Related
I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.
I'm running into an issue while using the Update syntax when updating a table row with a string. I'll post the code below then explain my issue:
$query = "SELECT * FROM foo WHERE bar = '$id'";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
for ($j = 0 ; $j < $rows ; ++$j) {
$entity_id=mysql_result($results,$j,'entity_id');
}
//$entity_id = "129";
if ($_POST['submit']) {
$text = mysql_real_escape_string($_POST['comments']);
$query = "UPDATE field_data_body SET body_value='$text' WHERE entity_id='$entity_id'";
mysql_query($query) or die ('Error updating database' . mysql_error());
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="comments">Example Comment</textarea>
<input name="submit" type="submit" value="submit" />
</form>
Here's a quick rundown of what the code does. I first request for the value of $entity_id from the table foo. I then update a different table row using a text-area and submit button.
My issue lies on line 12:
$query = "UPDATE field_data_body SET body_value='$text' WHERE entity_id='$entity_id'";
If $entity_id is passed directly to this line, the row will not update. If I assign an integer to $entity_id, (line 8 without the comment), the row will update. I've checked to make sure $entity_id is assigned a value before it gets to the submit section of the script; it returns 129, (echo "$entity_id"; output is 129). Why can I not pass the string without having to assign an integer?
EDIT: I found where the issue was taking place. The issue was on line 18, where the action attribute is called. I removed the php, and replaced it with a #. I'm not entirely sure why this was a fix to the problem, but there you have it. Thanks to those below with their suggestions and help, I do appreciate it!
I am currently tring to create a form wherein there is three dropdown option boxes and one submit button. All three of the dropdown boxes are populated from the database and I would like the selected options to be included into a new query and printed. This example only shows one dropdown
PHP Code
// Create connection
$con=mysqli_connect('', '', '', '');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$course_dropdown ="";
$query_course = "SELECT * FROM course";
$result_course = mysqli_query($con,$query_course) or die(mysqli_error());
while($row = mysqli_fetch_assoc($result_course))
{
$course_dropdown .= "<option value='{$row['CourseName']}'{$row['CourseName']} </option>";
}
Above is the code that is used to create the dropdown lists
HTML
<form="index.php" method="post">
<select name="Course"><?php echo $course_dropdown; ?></select>
<input name="button" value="Submit" type="submit">
I am at a loss over what way to proceed, I have tried various different techniques but cannot come up with an answer.
Latest attempt
$course = mysqli_real_escape_string($con, $_POST['Course']);
$query = mysqli_query($con,"SELECT * FROM course_module WHERE CourseName = $course");
this brought an error
Notice: Undefined index: Course in C:\Users\seanin\Desktop\xampp\htdocs\index.php on line 33
So have edited as suggested and stil have an error, may be missing something small.
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$course_dropdown ="";
$query_course = "SELECT * FROM course";
$result_course = mysqli_query($con,$query_course) or die(mysqli_error());
while($row = mysqli_fetch_assoc($result_course))
{
$course_dropdown .= "<option value='{$row['CourseName']}'>{$row['CourseName']}</option>";
}
if ($_POST['button'] == 'Submit') {
$course = mysqli_real_escape_string($con, $_POST['Course']);
$query = mysqli_query($con,"SELECT * FROM course_module WHERE CourseName = $course");
}
Still have this error
Notice: Undefined index: button in C:\Users\seanin\Desktop\xampp\htdocs\index.php on line 30
submit button issue
Nearly done, thanks for all the help so far.
What do I need to do to get the results and print them???
The reason why your dropdown is not working is missing " > "
replace the line inside while loop with this
$course_dropdown .= "<option value='{$row['CourseName']}'>{$row['CourseName']}</option>";
Please read about SQL injections. They can destroy your life.
I reckon that you are trying to access 'Course' in the following line and it is not defined:
$course = mysqli_real_escape_string($con, $_POST['Course']);
Are you able to submit the page? There is an error in your HTML form: <form="index.php" is not a valid HTML tag so you are not able to submit the page, that is if you posted the exact code you are using. Your form should be:
<form action="index.php" method="post">
<select name="Course"><?php echo $course_dropdown; ?></select>
<input name="button" value="Submit" type="submit">
</form> <!-- and don't forget the closing tag -->
You can check whether the page was submitted or not by doing something like this:
if ($_POST['button'] == 'Submit') {
$course = mysqli_real_escape_string($con, $_POST['Course']);
// please note the missing single quotes, and please read the first line of my answer
$query = mysqli_query($con,"SELECT * FROM course_module WHERE CourseName = '$course'");
}
There is also an invalid HTML syntax in the following line:
$course_dropdown .= "<option value='{$row['CourseName']}'{$row['CourseName']} </option>";
The format for <option> is: <option value="value">label</option>.
I need your help with my form. I'm trying to build a dynamic forms, whereby a specific integer entered in a previous form sp1.php is used to display the number of input boxes.
The variables from the first forms are $state and $number. Then on the handling page sp2.php, the value of $number is put into a for loop to display the input boxes.
What I'm trying to do now is that the values entered into the tinput boxes are inserted into a mysql table.
The error I'm getting are
1) Undefined Index : DISTRICT
2) Invalid Argument supplied for foreach()
Please how can I make this work. Thank you.
My Code is below.. I'll be more than happy to show other parts of the code, if required.
Thank you.
<?php
$state=htmlspecialchars(($_POST['state'])) ;
$number = intval(($_POST['number']));
for ($i = 0; $i < $number ; $i++ ) {
echo "
<form action='sd2.php' method='post'>
<label for='name'>Districts</label>
<input type='text' name='district[]'>
<br/><br/>
</form>";
}
?>
<?php
foreach($_POST['district'] as $senatorial) {
$query = "INSERT INTO state ( `state_id`, `state`, `senatorial`)
VALUES (NULL, '".$state."', '".$senatorial."') ";
mysql_query($query) or die (mysql_error());
}
?>
This must work:
$count = count($_POST['district']);
for ($i=0; $i<$count; $i++){
$district = $_POST['district'][$i];
//do this
//do that
}
I'm trying to check if a color is already entered into the database if it is the color should not be entered and stored into the database and the following error code <p>This color has already been entered!</p> should be displayed. But for some reason I cant get this to work, can someone please help me?
The color names are entered into $_POST['color'] which is an array entered by the user.
Here is the html code that collects the colors.
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
<input type="text" name="color[]" />
Here is the PHP & MySQL code.
for($i=0; $i < count($_POST['color']); $i++) {
$color = "'" . $_POST['color'][$i] . "'";
}
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color = '$color'
AND user = '$user_id' ");
if(mysqli_num_rows($dbc) == TRUE) {
echo '<p>This color has already been entered!</p>';
} else if(mysqli_num_rows($dbc) == 0) {
// enter the color into the database
}
To avoid unnecessary querys you should fetch all colors first and check against them:
$colors = array();
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
if($result = mysqli_query($mysqli,"SELECT color FROM colors WHERE user = '$user_id' ") {
while($row = mysqli_fetch_array($result)) {
$colors[] = $row['color'];
}
mysqli_free_result($result);
}
foreach($_POST['color'] as $color) {
if(in_array($color, $colors) {
echo '<p>Color ' . $color . ' has already been entered!</p>';
}
else {
// enter the color into the database
}
}
Make sure to sanitize the user input!
You have more than one colors so you should use something like following.
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
for($i=0; $i < count($_POST['color']); $i++) {
$color = "'" . $_POST['color'][$i] . "'";
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color = '$color'
AND user = '$user_id' ");
if(mysqli_num_rows($dbc) == TRUE) {
echo '<p>'.$color.' color has already been entered!</p>';
} else if(mysqli_num_rows($dbc) == 0) {
// enter the color into the database
}
}
I'm guessing the issue you're runnig into is that the database connection is allready open when you try to enter the new values into the database.
The solution is to first fetch everything from the database store it in an array, then run your checks and add accordingly.
You should use the IN operator. For example,
$color = null;
for($i=0; $i < count($_POST['color']); $i++) {
if ($color == null)
$sep = '';
else
$sep = ',';
$color = $sep . "'" . $_POST['color'][$i] . "'";
}
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT *
FROM colors
WHERE color IN ($color)
AND user = '$user_id' ");
It isn't an answer actually, but very important thing to learn:
I mean the simple thing: at first you have to deal with SQL only, no PHP or HTML. Create an SQL query to check for the colors, run it, test it, and once you statisfied - go for PHP. try to create the same query from a variable, and compare with example one. Once finished, you can go for HTML at last.
So, development process must be split into 3 stages:
SQL stage. Create a query. If you don't know what query you want, Ask here on SO somethink like "I have 3 color names and a table. how to check if any of these colors exists in the table already". Once done - check it out to ensure query runs ok and return desired results.
PHP stage. Once you have a query, echo it from your PHP script. And write a code below, code which produce this query from some variables. Print it out to compare, until you get both queries identical.
HTML stage. Make an HTML form which will send color names into PHP script which will create SQL query from them and finally run it.
Remember: to know which query you want to run is very-very important! Without this knowledge you cannot go any further
Every answer here lack to mention SQL query itself.