Only the top most switch works in my website - php

I'm using HTML, PHP and Ajax to toggle switch in my website. However, only the top most switch is functional. The reason why I use PHP is to display results from my DB, and Ajax is there to toggle switch without reloading the website. Thanks in advance and comment for any questions!
Photo Here :D I have three rows in the DB. Data retrieve fine. Top button works!
ps : removed all classes for simplicity
About main.php and recipe.inc.php. They are separated because recipe.inc.php is used in many documents.
main.php
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID" name="recipe_ID" value="';
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus" name="checkStatus" checked="">';
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus" name="checkStatus">';
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
}
?>
recipe.inc.php
<?php
if(isset($_POST['checkStatus'])){
$recipe_ID = $_POST['recipe_ID']);
if($_POST['checkStatus']=='ON'){
$status = 1; //to save in DB as boolean. if ON->1
}else if($_POST['checkStatus']=='OFF'){
$status = 0; //if OFF->0
}
$sql = "UPDATE `recipe` SET `status`=$status WHERE creator=$uid AND recipe_ID=$recipe_ID";
//nev
mysqli_query($conn,$sql);
}
?>
and the Ajax part is saved in another js file.
recipe.js
$(document).ready(function() {
$('#checkStatus').on('click', function() {
var checkStatus = this.checked ? 'ON' : 'OFF';
var recipe_ID = $("#recipe_ID").val();
$.post("loginsystem/includes/recipe.inc.php", {
"checkStatus": checkStatus,
"recipe_ID": recipe_ID
},
function(data) {
$('#checkStatus').html(data);
});
});
});

That sounds like all the switches have the same ID. If that is the case, only the first one will work.
Try changing your code to look like this:
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$cnt = 1;
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID-' .$cnt. '" name="recipe_ID" value="'; <============== HERE
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus" checked="">'; //<============== HERE
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus">'; //<================ HERE
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
$cnt++; <=========== HERE
}
?>

Related

How to display checked checkbox from database in php?

I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.

Unable to use an array as an array?

I am in the process of building a software download site for my company.
However, I have come across a problem that I am unsure how to get past.
I am retrieving all the information from a table about a particular software release and placing them in a multidimensional array. I am then trying to run a foreach (I have even tried a for loop) against that array and I get an error shown below:
When I run var dump against the original array, I get this:
So I am really confused as I don't know what I'm missing or where I am going wrong. The reason why I want to run this is so that I can filter the array into a one dimensional array.
Below is the code for the main web page
<?php
//Displays list of companies in 2 columns
$versionAccess = VersionAccess::findAccess($relId);//This gets set earlier in the webpage
$count = count($versionAccess);
var_dump($versionAccess);
foreach ($versionAccess as $va)
{
if ($va->company_access != '0')
{
$versionAcc[] = $va->comapny_id;
}
}
foreach ($company as $compAccess)
{
$compAccessId = $compAccess->company_id;
if (in_array($compAccessId, $versionAcc))
{
$access = 'checked disabled';
}
else { $access = 'disabled'; }
$accessName = 'access'.$compAccessId;
if ($ctr % 2 == 0)
{
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
else
{
if ($ctr < $compCount)
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
}
else
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
}
$ctr++;
}
?>
The function that brings the data from the database is:
public static function findAccess($accessId)
//find the version access in database
{
return self::findQuery("SELECT * FROM version_access WHERE version_id = '$accessId'");
}
The findQuery method:
public static function findQuery($sql)
{
global $database;
$resultSet = $database->query($sql);
$objectArray = array();
while ($row = mysqli_fetch_array($resultSet))
{
$objectArray[] = self::instant($row);
}
return $objectArray;
}
I am still relatively new and any help is greatly appreciated.

multiple forms handled by one script php

I try to create an order page on php. I have created a form which stores data into the database. The form number is based on the user and it is created dynamic.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<form action="user_order_form.php" method="POST">';
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
echo '</form>';
}
}
?>
So I have many forms and 1 script to handle them. If I submit 1 form then it applies the data to the database but the other forms dissapear. This is the second php 'handler'.
<?php
if (isset($_POST['submit']))
{
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
$item = $_SESSION['item'];
$temp = $_POST['yliko'];
$temp2 = implode(",", $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
?>
I want to submit all the forms. Should I try to create one submit button for all of the forms or is there a way to handle all of them separately ?
You can have many submit forms, but simply define one big <form> with all of them, then you will not lose any information.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
}
echo '</form>';
}
?>
now you can also add the ~$i~ identifier to input names, so you can easily distinguish which is which.

Reduce number of MySQL Queries and Output Data in Correct Order

My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.

php how to divide a list of while loop result

PHP:
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
echo '<p><input type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
RESULT:
<input type="checkbox" value="Crows feet">Crows feet
<input type="checkbox" value="Frown lines" >Frown lines
<input type="checkbox" value="Lip augmentation">Lip augmentation
<input type="checkbox" value="Lip lines">Lip lines
<input type="checkbox" value="Marionette lines">Marionette lines
i want the result:
**LEFT** **RIGHT**
<input type="checkbox">Crows feet |<input type="checkbox" >Lip lines
<input type="checkbox">Frown lines | <input type="checkbox">Marionette lines
<input type="checkbox"">Lip augmentation
Could you not alternate a class on each second input that suggests clearing a float or something similar if you are not floating the inputs? Something along the lines of:
function get_t_wrinkle_rel(){
global $mysqli;
$flag = 1;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
if ($flag = 1) {
$orientate=left;$flag=0;
} else {
$orientate=right;$flag=1;
}
echo '<p><input class="' . $orientate . '"type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
while ($left = $q->fetch_array()) {
echo '<p>';
echo '<input...>' . $left['...'];
if ($right = $q->fetch_array()) {
echo '| <input...>' . $right['...'];
}
echo '</p>';
}
This way should fill the left column in order then the right column, keeping the order you want to achieve. I don't have access to your database so I can't test this, but it should do the job.
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
$mid = floor($q->num_rows/2); // Get halfway point
$count = 0;
$array = array();
while($r = $q->fetch_array()){
$string = '<input type="checkbox" value="'.$r['t_wrinkle_name'].'" />'.$r['t_wrinkle_name'];
if($count <= $mid){
// Left column
$array[$count] = $string;
} else {
// Right column
$array[$count-$mid] .= '|'.$string;
}
$count++;
}
// Make single string
echo implode('', $array);
}
However I would recommend using the idea biscuitstack suggested, using CSS to position it the way you want, rather than doing it programatically. It's always better to try to keep presentation separate from the logic wherever possible.
You could use flag that increments everytime and
<input type="checkbox"' . $r['t_wrinkle_name'] .
if flag % 2 == 0 then echo '<br />'
Or something like that.

Categories