Convert DB string into checkbox checking with PHP - php

I have following SQL query:
$readNews_SQLselect = "SELECT ";
$readNews_SQLselect .= "live, content, user, created, created_updated, user_updated "; // rows names
$readNews_SQLselect .= "FROM ";
$readNews_SQLselect .= "news "; // table name
$readNews_SQLselect_Query = mysql_query($readNews_SQLselect);
And while loop to display the data from DB:
while ($row = mysql_fetch_array($readNews_SQLselect_Query, MYSQL_ASSOC)) {
$LIVE = $row['live'];
$CONTENT = $row['content'];
$USER = $row['user'];
$CREATED = $row['created'];
$USER_UPDATED = $row['user_updated'];
$CREATED_UPDATED = $row['created_updated'];
echo '<input type="checkbox" value=" '.$LIVE.'" />';
echo '<input value=" '.$CONTENT.'" />';
echo '<p>'.$USER.'<p/>';
echo '<p>'.$CREATED.'<p/>';
echo '<p>'.$USER_UPDATED.'<p/>';
echo '<p>'.$CREATED_UPDATED.'<p/>';
}
mysql_free_result($readNews_SQLselect_Query);
As my echo '<input type="checkbox" value=" '.$LIVE.'" />'; will be either '0' or '1' - how can I convert this string into checkbox checking / unchecking with PHP?
Any suggestion much appreciated.

You'll want to use an In-Line If Statement.
echo '<input id="chkLive" type="checkbox"'.(($LIVE=='1') ? ' checked ' : '').'/>';

I don't know if I understand correctly, but you only want to display which ones are checked, right?
echo '<input type="checkbox" ',($LIVE ? 'checked="checked"':''),'/>';

if $live is your variable which is either 0 or 1,
then you can use:
$boxCheck = '';
if($LIVE == '1')
{
$boxCheck = 'checked="checked"';
}
else
{
$boxCheck = '';
}
echo '<input type="checkbox" value=" '.$LIVE.'" '.$boxCheck.'/>';

$checked = ($LIVE) ? 'checked="checked"' : '';
echo '<input type="checkbox" '.$checked.' value=" '.$LIVE.'" />';

Related

how Insert the answers of questions into database with same radio button name?

how to pass the answers id to insert it into DB with same name of the radio button? because when I tried to insert the answers ids, the written code inserted the answers ids for the first if statement only
<div class="coursebox">
<?php
echo '<div class="question-box" style="border-bottom: 0;"><h2>';
str('assess_exam');
echo'</h2></div>';
if($questions = $wpdb->get_results("SELECT * FROM evaluation_test WHERE year = 'half_year'")){
echo '<form method="POST">';
echo '<input type="hidden" value="'. sizeof($questions) .'" name="num_of_ques" />';
$q_counter = 1;
foreach ($questions as $q) {
echo '<div class="question-box">';
$ques = $l == 1 ? $q->q_en : $q->q_ar;
echo '<p>'. $ques .'</p>';
echo '<input type="hidden" value="'. $q->id .'" name="q_id[]" />';
if($answers = $wpdb->get_results("SELECT * FROM evaluation_answers WHERE q_id = $q->id")){
foreach ($answers as $ans) {
$a = $l == 1 ? $ans->ans_en : $ans->ans_ar;
echo '<label><input type="radio" value="'. $ans->id .'" name="q_'.$q_counter.'_ans" required checked />'. $a .'</label>';
}
}
echo '</div>';
$q_counter++;
}
echo '
</form>
';
}
echo '<div class="question-box" style="border-bottom: 0;"><h2>';
str('assess_exam');
echo'</h2></div>';
if($questions = $wpdb->get_results("SELECT * FROM evaluation_test WHERE year ='one_year'")){
echo '<form method="POST">';
echo '<input type="hidden" value="'. sizeof($questions) .'" name="num_of_ques" />';
$q_counter = 1;
foreach ($questions as $q) {
echo '<div class="question-box">';
$ques = $l == 1 ? $q->q_en : $q->q_ar;
echo '<p>'. $ques .'</p>';
echo '<input type="hidden" value="'. $q->id .'" name="q_id[]" />';
if($answers = $wpdb->get_results("SELECT * FROM evaluation_answers WHERE q_id = $q->id")){
foreach ($answers as $ans) {
$a = $l == 1 ? $ans->ans_en : $ans->ans_ar;
echo '<label><input type="radio" value="'. $ans->id .'" name="q_'.$q_counter.'_ans" required checked />'. $a .'</label>';
}
}
echo '</div>';
$q_counter++;
}
echo '
</form>
';
}
if(current_user_can('teacher')){
echo '<button type="submit" name="save_report">'; echo $get_strings->save_report[$l]; echo'</button>';
}
?>
</div>
and here is the insert code
if(isset($_POST['save_report'])) {
$user_id = $_POST['profile_id'];
if(!$wpdb->get_results("SELECT * FROM multi_evaluation_answers WHERE user_id = $user_id AND type = 'evaluation-test' ")) {
$wpdb->get_results("SELECT * FROM evaluation_test ");
$q_array = $_POST['q_id'];
$num_of_ques = $_POST['num_of_ques'];
for($i = 1; $i <= $num_of_ques; $i++) {
$question_id = $q_array[$i-1];
$answered_id = $_POST['q_'.$i.'_ans'];
$sql = "INSERT INTO multi_evaluation_answers(q_id, answered_id, user_id, type , test_type, answer_value )VALUES($question_id, $answered_id, $user_id ,'evaluation-test', 'age_move', (select ans_value FROM evaluation_answers WHERE id = $answered_id))";
$wpdb->query($sql);
}
}
I need to insert the answers ids into database table with same name of the radio button, could you please guide me who to do it.
Thank you so much.

send table row to next page

Im trying to make a simpel webshop where I list some items (to order) on each row there is a form field for tell how many the costumer wants of the item. Then she submit a button and the action is another page where the item will be added to an MYSQL table to be processed later Im thinkking that when user hit the submit there is a hidden field that send the itemid.
I need to get a way to make the itemid with me to the other side but I cant make the variable specific for the row. the ArtikelNR variable $row["ArtikelNr"] shoudld be assigned to the hidden form and be accessable on next page as ArtikelNr = $_REQUEST['ArtikelNr']; and it works so far but it always the laast item number not the itemnumber that i specific for the choosen row. How do I make $form4 = ' '; row speciific so i can catch it on next page and add it to the basket.
<?php include 'databas_connect.inc'; ?>
<?php
$sql = "SELECT `ArtikelNr`, `ArtikelNamn`, `Storlek`, `ArtikelPris`,
`artikelbild`FROM `artiklar` ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>Antal</th><th>ArtikelNr</th><th> ArtikelNamn</th>
<th>Storlek</th><th>ArtikelPris</th><th>Artikelbild</th></tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
$number =1;
$artnr = $row["ArtikelNr"];
$prefix = "pre_";
$sufix = 1;
${$prefix .$sufix} =$row["ArtikelNr"] ;
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.${$prefix .$sufix}.'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 ;
$img = "<img src=./img/>";
$image=$row['artikelbild'];
$path ="<img src='./img/".$image."' />";
echo "<tr><td>" .$form. "</td><td>" . $row["ArtikelNr"]. "</td><td>" .
$row["ArtikelNamn"]. " </td><td> " . $row["Storlek"]. " </td><td>" .
$row["ArtikelPris"]. " </td><td>".$path."</td></tr>";
++$sufix;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
here is code for sida61.php
<?php include 'databas_connect.inc'; ?>
<?php
session_start();
$ArtikelNr = $_REQUEST['ArtikelNr'];
$antal = $_REQUEST['antal'];
//$KundNr = $_SESSION["Kund"];
// attempt insert query execution
$sql = "INSERT INTO `kundkorg`( `ArtikelNr`, `antal`, `KundNr`)
VALUES (1,$antal, 2)";
if(mysqli_query($conn, $sql)){
print_r($_REQUEST); // I just do this to se value of $_REQUEST it is always 8 since I have 8 items i dont know why
}
else
{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($conn);
}
// close connection
mysqli_close($conn);
//header("Location: 6.php");
?>
Not sure why you were attempting to add a prefix and a suffix as you say you want to pass just the $row["ArtikelNr"] in your hidden field.
You also missed concatenating your </form> closing tag into your $form variable.
So this code should achieve what you want.
while($row = $result->fetch_assoc()) {
$form .= '<form action="sida61.php" method="post">';
$form .= '<label for="antal"></label>';
$form .= '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form .= "<input type='hidden' name='ArtikelNr' value='{$row['ArtikelNr']}'/>";
$form .= '<input type="submit" name="btn_submit" value="KÖP" />';
$form .= '</form>';
$img = "<img src='./img/{$row['artikelbild']}'/>";
echo "<tr><td>$form</td><td>{$row['ArtikelNr']}</td><td>
{$row['ArtikelNamn']}</td><td>{$row['Storlek']}</td><td>
{$row['ArtikelPris']</td><td>$path</td></tr>";
}
Yes I se now I missed to missed concatenating your closing tag into $form variable. the correct code is
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1"
id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.
$row["ArtikelNr"].'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 . $form6 ;
Thanks so much #RiggsFolly
When I tried your code it added a new form on each row making me have 9 input fields on row 9. but You helped me anyway!!

PHP variables inside HTML Code

I am making a student sign-up form using html and php.
First you are asked to insert your name, password and email and when you click submit, it takes you to another page (ChooseDepartment.php) in which you get a list of all departments from my database to choose your own.
Now, I am a total newbie, so here is the part of my php code that I am stuck with in ChooseDepartment.php:
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />"."Available departments: "." ".mysql_num_rows($ShowPossibleDep)."<br />";
echo "<br />";
echo '<form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=<?php $row['DEPT_ID'] ?>>';
echo "<br />";
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment">';
echo </form>;
}
I am trying to make the value of the radio button carry the value of the
the department id so I can then update my database with the student's department which is currently NULL, but I can't figure out how to use both html and php at the very same line correctly! This gives me syntax error!
as you're in PHP, so you don't need to open and close PHP tag.
The reason you're getting Syntax error is just because you're not manipulating string properly.
error is with this line
echo '<input type="radio" name="department" value=<?php $row['DEPT_ID'] ?>>';
^ here ^ here
So you need to remove the PHP tags and need to concatenate string properly like:
echo '<input type="radio" name="department" value="'.$row['DEPT_ID']. '">';
and with this one
echo </form>;
you're missing quotes around form tag. So it should be,
echo '</form>';
There are some other typos are as well, so your final code will be look like this.
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />Available departments: ".mysql_num_rows($ShowPossibleDep);
//echo "<br />"; add this <br /> tag to next echo
echo '<br /><form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=" '.$row['DEPT_ID'].'"><br />';
//or you can do this way
//echo "<input type='radio' name='department' value='$row[DEPT_ID]'><br />";
//echo "<br />"; appended in upper statement.
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment"></form>';
//echo </form>; closed already(above statement).
}
and without comments, more cleaner :)
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />Available departments: ".mysql_num_rows($ShowPossibleDep);
echo '<br /><form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=" '.$row['DEPT_ID'].'"><br />';
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment"></form>';
}
Take a look at string operators
http://php.net/manual/en/language.operators.string.php
You can combine two strings in php with a dot, so that part of your code would become this:
{
echo $row['NAME'];
echo '<input type="radio" name="department" value="'.$row['DEPT_ID'].'">';
echo "<br />";
}
No need to open php tag again
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0) {
echo "<br />"."Available departments: "." ".mysql_num_rows($ShowPossibleDep)."<br />";
echo "<br />";
echo '<form id = "dept" action = "Courses.php" method = "post">';
while ($row = mysql_fetch_array($ShowPossibleDep)) {
echo $row['NAME'];
echo '<input type="radio" name="department" value="' . $row['DEPT_ID'] .'">';
echo "<br />";
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment">';
echo "</form>";
}

Invalid argument supplied for foreach() - Yet output is showing

I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the "Invalid argument supplied for foreach()" warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
Here is the code:
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' ORDER BY RECORD";
$data = mysqli_query($dbc, $query8);
echo '<pre>' . print_r($data, true) . '</pre>';
$rowcount = 1;
while ($row = mysqli_fetch_assoc($data))
{
if (is_array($row))
{
echo '<p> It is an Array</p>';
}
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
echo 'Rowcount' . $rowcount. '</br>';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ( (!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="major">Field of study:</label>';
echo '<input type="text" id="major" name="major" size="40" maxlength="40" value="' . ( (!empty($major)) ? $major : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
$rowcount++;
}
}
;
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
foreach ($row as &$item)
replace this with:
foreach ($row as $item)
And then for each variable you should probably change
$record = $row['RECORD'];
to
$record = $item['RECORD'];
foreach($row as &$item) should be
foreach($row as $item)
there is no need to use the foreach here you can just do this like like
while ($row = mysqli_fetch_assoc($data))
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
}
You're not changing the row item, so don't pass by reference to the foreach. Also, shouldn't you be using $item instead of $row? Do this:
foreach($row as $item)
{
$record = $item['RECORD'];
$school = $item['SCHOOL'];
....
Don't do This:
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
....

Check Checkbox depending on value in database

I have an code that gets the 'branches' from the database. Each company can have multiple 'branches'.
Only thing is, that is doesn't work. Can you guys figure out what's wrong?
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while($rijbranche = mysql_fetch_assoc($querygetbranches))
{
echo "<tr>";
echo "<td width='400'>";
echo $rijbranche['naam'];
echo "</td>";
echo "<td>";
$get2 = "SELECT * FROM bedrijf_branche WHERE bedrijf_id = '$id'";
$query2 = mysql_query($get2);
while ($rij20 = mysql_fetch_assoc($query2))
{
$branche_id = $rij20['branche_id'];
}
if($branche_id == $rijbranche['id_branche']){
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" CHECKED></input>
<?php
}
else
{
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>"></input>
<?php
}
echo "</td>";
}
Try the following code
<?php
$id = $_GET['id'];
// Output BRANCHES
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while ($rijbranche = mysql_fetch_array($querygetbranches)) {
echo ' <tr>' . "\n";
echo ' <td width="400">' . $rijbranche['naam'] . '</td>' . "\n";
// Output CHECKBOX
$get2 = mysql_query("SELECT * FROM bedrijf_branche WHERE bedrijf_id = '" . $id . "' AND branche_id = '" . $rijbranche['id_branche'] . "'");
$rij20 = mysql_fetch_array($get2);
$branche_id = $rij20['branche_id'];
if ($branche_id == $rijbranche['id_branche']) {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" checked="checked" />';
}
else {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" />';
}
echo ' <td>' . $checkbox . '</td>' . "\n";
echo ' </tr>' . "\n";
}
?>
Found a couple of errors I fixed in the above code.
You're closing the <input> fields incorrectly
Your second while() loop is unnecessary as there should only be one row returned
You have to add branche_id to your second mysql_query!
Don't close and re-open your <?php ?> tags for every HTML line when you can just add an echo
Your HTML-syntax is wrong.
The way you close the input tag and the way you want to check the chechbox is wrong
Try this
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" checked="checked" />

Categories