variable array is only populating last row of mysql table - php

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)

Related

How to select rows from array of keys?

I have a table and the primary key is 'unique_identifier'. I would like to select the rows from a number of keys. I have an array that contains the keys who's data from the table I would like to select and retrieve all at once. Please set aside security concerns.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier='????????????";
$result = $mysqli -> query($sql);
$count = $result -> num_rows;
if($count > 0){
echo 'count: '.$count;
}else{
echo 'error';
}
You can use implode function of PHP and IN operator of SQL.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier in ('" . implode("','", $myArray) ."')";
Suppose you have name, roll, email in a table.After completing your sql that you have done you can access every attribute by this way.
while($row = $result->fetch_assoc()){
$name = $row["name"];
$email = $row["email"];
$roll = $row["roll"];
}

how to store two checkbox values in mysql db using php

i have multiple checkbox values in my form as shown in figure
I know i can store values for single checkbox in db but here situation is slightly different,so ho could i successfully store them in different different rows for same db.
my table struture is
1.content_table
title,description,category_id(fk),course_id(fk),subject_id(fk),content_type_id(fk)
2.category_table
entrance,school,ug,pg
3.subject_table
english,hindi,maths......
4.content_type_table
notes,summary,videos,question_bank
i have to insert data from shown form in content_table which store data by category_id,course_id,subject_id,content_type_id
i have tried following code which is only working for single checkbox i.e category ,so please someone suggest me how to do for different type of checkbox.
my code is
<?php
include 'includes/dbconfig.php';
if($_SERVER['REQUEST_METHOD']=='GET')
{
echo $title = $_GET['title'];
echo $description = $_GET['description'];
echo $content_url = $_GET['content_url'];
echo $thumb_icon_url = $_GET['thumb_icon_url'];
$category = $_GET['category'];
$course = $_GET['course'];
echo $select_subject = $_GET['select_subject'];
echo $select_content_type = $_GET['select_content_type'];
foreach (array_combine($category, $course) as $cat => $cose) {
$sql = mysqli_query($conn,"SELECT category_id from category_ref_table where category = '$cat'") or die(mysqli_error());
$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
echo $category_id = $row['category_id'];
$sql1 = mysqli_query($conn,"SELECT course_id from course_ref_table where course = '$cose'") or die(mysqli_error());
$row1 = mysqli_fetch_array($sql1,MYSQLI_ASSOC);
echo $course_id = $row1['course_id'];
$sql2 = mysqli_query($conn,"SELECT subject_id from subject_ref_table where subject = '$select_subject'") or die(mysqli_error());
$row2 = mysqli_fetch_array($sql2,MYSQLI_ASSOC);
echo $subject_id = $row2['subject_id'];
$sql3 = mysqli_query($conn,"SELECT content_type_id from content_type_table where content_type = '$select_content_type'") or die(mysqli_error());
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
echo $content_type_id = $row3['content_type_id'];
mysqli_query($conn,"INSERT INTO content_ref_table (title,description,content_url,thumb_icon_url,category_id,course_id,subject_id,content_type_id,login_id)VALUES ('$title','$description','$content_url','$thumb_icon_url','$category_id','$course_id','$subject_id','content_type_id')");
}
}
?>
try something like this(array variable)
<input type="checkbox" name="category[]" value="entrance">
<input type="checkbox" name="category[]" value="School">
<input type="checkbox" name="category[]" value="ug">
<input type="checkbox" name="category[]" value="pg">
Upon using like this you can get the list of checked items as an array. After that do the required save it in your table.

Get the column names and field values for one record using MySqli

I am trying to get the column names and field values from a table for ONE record. If a column name was 'sellers' and the field value was 'Bob', the desired output would be: seller Bob
The output will actually be used for a script like this:
$fields['sellers']->setValue($sellers);
Where 'sellers' is the column name and $sellers is the field value.
There are dozens of columns in the table.
The script below only outputs the column names - not the field values.
Any help is appreciated.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ';
while ($row = mysqli_fetch_array($sql_result)) {
$data = $row[$col];
echo $data."<br>";
}
}
Not sure if I exactly understand what you're trying to do but would using mysqli_fetch_assoc() and a foreach loop give your desired result?
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($sql_result);
foreach($row as $column => $value) {
echo $column . " " . $value;
}
You should just call mysqli_fetch_array() once, not in a loop for each column. Because every time you call it, it moves to the next row of results, it doesn't re-fetch the old row. Since you only have one row of results, the repeated calls just return false.
$row = mysqli_fetch_array($sql_result);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ' . $row[$col];
}
But there isn't really any need to use mysqli_fetch_field() to get the field names. Since $row is an associative array, the field names are just the keys of the array. However, it would be better to use mysqli_fetch_assoc(), because mysqli_fetch_array() returns an array that contains both named and numbered elements; mysqli_fetch_assoc() just returns the named elements. So the answer by WheatBeak is how most would do what you want.
I think that there's a problem with the interpolation.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
Using variables between apostrophes sends the string "$trans_id" in the SQL query instead of the value which $trans_id contains. Try this:
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '" . $trans_id . "' ";

How to display the content of more then one SQL database row

I am trying to retrieve the data stored in an unknown number of mySQL database rows and display them using HTML. At the moment I can display data from one row.
Each row has a unique id number, I was planning to iterate through by comparing this number to the variable counter. But it would then leave me with the issue of displaying the results in HTML. At the moment I am just echoing variables that contain data from the rows. However what I want to create is a HTML list that increases in length depending on how many rows are in the table.
Here is my current PHP code for retrieving a row from the database is:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
$row = $query->fetch_assoc();
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
At the moment I am just displaying some of the results in HTML using this code:
<div id="inner_container">
<?php echo "$task_id $proj_name $task_name $task_deadline"; ?>
</div>
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
while($row = $query->mysqli_fetch_assoc()) {
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
echo "$task_id $proj_name $task_name $task_deadline";
}
Since you have built an associative array using fetch_assoc all you need to do is loop through that array. The OO example on http://php.net/manual/en/mysqli-result.fetch-assoc.php should get you what you need. A quick example:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
echo '<div id="inner_container">';
while ($row = $query->fetch_assoc()) {
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_deadline = $row["task_deadline"];
echo "$task_id $proj_name $task_name $task_deadline";
};
/* free result set */
$row->free();
echo '</div>;

Input checkbox value that is created dynamically into MySQL if checked

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
}

Categories