I am pulling in questions from a questions table in MySQL and populating them in a form. This works fine and I am populating checkboxes as well that the value is populated with the QuestionID. The array is properly populating but I want to take the value of the checked checkboxes (which is my question ID) and insert that ID into a table, so that I have the questions that are selceted for use by their ID. Here is what I have so far:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name=chkQuestion align="left"/><p>' . $row['Question'] .'</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
if (isset($_POST['chkQuestion']))
{
//create the query for the score
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES ($QuestionID)";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Submitted!!</h1>';
}
}//End of IF 'submitted
You want to insert multiple records in one statement is what I'm understanding.
$sql2 = "INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(". implode('),(', $QuestionID) . ")";
This will join each index inside $QuestionID with ),(
If you were to echo $sql2 you would get
INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)
You can use a loop to get the questions that are checked.
for($i=0;$i<count($_POST["chkQuestion"]);$i++) {
"INSERT INTO tbl_QuestionSelected (QuestionID) VALUES('".$_POST["chkQuestion"][$i]."');
}
This way the MySQL statement has the actual values to insert into your table.
try to loop your ids and escape it!!
$ids_list = '';
foreach($_POST["chkQuestion"] as $id)
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
This will assign the value based on the array for the value and insert it into MySQL:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name="QuestionID[' . $row['QuestionID'] . ']">' .$row['Question']. '</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
$ids_list = '';
foreach($_POST["QuestionID"] as $key=>$value) {
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($value);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
}//End of IF 'submitted
}
Related
The table deportes has 2 columns with 4 rows:
<?php
$sql = 'SELECT * FROM deportes';
$resul = mysqli_query($conexion, $sql);
$deportes = array();
while ($fila = mysqli_fetch_array($resul))
{
$deportes[] = $fila;
}
?>
The form with the select multiple options:
<select name="fan[]" multiple="multiple">
<?php
foreach ($deportes as $aficion)
{
echo "<option value='".$aficion['idD']."'";
echo " >{$aficion['nombreDep']} </option>\n";
}
?>
</select>
Get the values from the form
<?php
if (isset($_POST['fan']))
{
$sport = $_POST['fan'];
}
?>
Now this
<?php $sport = mysqli_real_escape_string($conexion, $sport); ?>
This way insert the values in another table
$idPersona = mysqli_insert_id($conexion);
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
And the result is i get the value "0" in the field idD from table mec
If you print_r your $_POST['fan'], you will see that this is array. To get every value of array you should iterate over it, with for or foreach:
$idPersona = mysqli_insert_id($conexion);
foreach ($_POST['fan'] as $sport) {
echo $sport; // you will see that now it is string
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
// execute your query
}
And of course you must move to prepared statements to protect your code from sql-injection. This question will give you a start.
I am calling back the results for AnswerStatusID and AnswerResponse and need to apply them to a variable to compare against to see if the answer given is correct or incorrect and the corresponding response for the answer, my issue is that my variable is only being populated by the last row in the table instead of populating it with all of the data.
// Connect to the Database
require_once('mysqli_connect.php');
//create the query for the question
$q = "SELECT `Question` FROM tbl_Question WHERE QuestionID = 1";
//Create the query for the Answers
$q2 = "SELECT `Answer`,`AnswerStatusID`,`AnswerResponse` FROM tbl_Answer WHERE QuestionID = 1";
//Run the query
$r = mysqli_query($conn,$q);
//run the answer query
$r2 = mysqli_query($conn,$q2);
while($row = mysqli_fetch_array($r,MYSQLI_ASSOC)){
echo '<div id="Question1"><p>1) ' . $row['Question'] . '</div></p>';
}
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$AnswerStatusID.'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse = $row2['AnswerResponse'];
}
As Wiseguy intimated, it looks like you want AnswerStatusID and AnswerResponse as arrays.
Two steps here. First declare them as arrays.
$AnswerResponse = array();
$AnswerStatusID = array();
Then store the values in each of them
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$AnswerStatusID.'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID[] = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse[] = $row2['AnswerResponse'];
}
You can then see what's in the arrays using var_dump();
var_dump($AnswerResponse)
or
print_r($AnswerResponse)
I have an array that grabs checkbox data and posts certain information into the database if the checkbox data isn't a copy of something already in the database. What I would like to know is how can I create a code that scans through the database and finds data that wasn't part of my checkbox data and delete it from the database.
Okay, for example let's say I have values 1,2,3,4 in my database, but in my checkboxes I only get back 1,2,4. I would like a code that scans my database and deletes that value(s) (in this case 3) from the database.
Here is my current code:
foreach($_POST['publish'] as $index => $val){
$matches = mysql_query("SELECT * FROM `$blog_table` WHERE `postID` = '$val");
if (mysql_num_rows($matches) > 0)
{
// do nothing
} else {
$query3 = "insert into `$blog_table`
(`postID`)values
('$val')";
mysql_query($query3);
}
}
Here would be the code I would use with escaped input
if (!empty($_POST['publish']))
{
$inserts = array();
$deletes = array();
foreach ($_POST['publish'] as $val)
{
$deletes[] = intval($val);
$inserts[] = '('.intval($val).')';
}
$delete = "DELETE FROM `".$blog_table."` WHERE postID NOT IN (".implode(',',$deletes).");";
$insert = "INSERT INTO `".$blog_table."` (`postID`) VALUES ".implode(',',$inserts)."";
}
you should use query like this:
delete from table where id NOT in (3)
in php like:
$query = "DELETE FROM `$blog_table` WHERE `postID` NOT IN (" . implode(',', $array) . ")";
For the MySQL query, you can use NOT IN:
DELETE FROM tablename
WHERE col1 NOT IN (1, 2, 4)
i have an array of company name, i insert each company name as separate record.below is the code
<input type="text" name="company_name[]">
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
$val="('".implode("'), ('",$mycompany)."')";
$sql = "INSERT INTO `table`
(`company_name`) VALUES ".$val."";
The above query look like this and it successfully inserted 2 records in table.
INSERT INTO `table` (`company_name`) VALUES ('DELL'), ('IBM')
Now the problem is that with every company_name there is a company_code which i want to insert with each record and there is 3rd values lets suppose order_num which i also want to insert but the order_num should be same in all records,i need the query below
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89'), ('123','IBM','bxc90')
Okay, at last you endeavored to produce something understandable
1) This this code is absolutely useless:
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
as $mycompany being an exact duplicate of $company_name
2) To get your "very complex" query
foreach($_POST['company_name'] as $key => $value)
{
$name = mysql_real_escape_string($value);
$code = mysql_real_escape_string($_POST['company_code'][$key]);
$mycompany[] = "(123,'$name','$code')";
}
$sql = "INSERT INTO `table` (order_num,company_name,company_code) VALUES ";
$sql .= implode(",",$mycompany);
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89');
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','IBM','bxc90');
You can use an array
$arrray_to_be_inserted=array
(
[0]=>array('123','DELL','axc89'),
[1]=>array('123','IBM','bxc90')
);
Instead of passing value to a new variable in foreach , try to access as $key and $value, try this and see if it can help you
<?php
$company_name = array("DEL","IBM");
$company_code = array("1","2");
$order_num = array("4","5");
if($company_name)
{
foreach($company_name as $key => $value)
{
$mycompany[] = $value;
$mycompanycode[] = $company_code[$key];
$myordernum[] = $order_num[$key];
}
}
?>
Just make sure names and their values are corresponding to each other .
i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}