Disable checkbox based on db value - php

I have a checkbox in a form which I need to disable based on the value in the database. I searched a lot, but can't find any solution that works. Here's the sample code:
<?php
$server_name='localhost';
$username='root';
$password='';
$db_name='checkbox';
$con= mysqli_connect($server_name, $username, $password, $db_name);
if(mysqli_connect_errno())
{
echo 'Failed..!!'.mysqli_connect_errno();
}
$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
$disable = $display?'':'disabled="disabled"';
?>
<html>
<body>
<form name="f1" method="post" action="test2.php">
<input type="checkbox" name="A" value="" <?php echo $disable; ?> />
</form>
</body>
</html>
Thanks in advance.

Far as I can tell, it seems that you may have gotten your ternary's order mixed up.
Now this line is redundant:
$display = (mysqli_num_rows($result) == 1);
You're telling it that it always equals TRUE.
Just set this line to:
$display = mysqli_num_rows($result);
Then the ternary operator will take care of if it's found or not:
$disable = $display ? 'disabled="disabled"': '';
...and if found, disable it.
If that isn't what you're looking to do, then change it back to:
$disable = $display ? '': 'disabled="disabled"';

$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
Is likely the cause of your problems though it can't be 100% without looking in the database. Does that query return something other than one row? If it does your $display variable will always evaluate to false and not add that disable text to the input field.
Wrap the $disable variable in a var_dump() before you get to the rendering of HTML and see what value you are getting. Or do a direct database query with the one you are triggering off of and see if it is something other than one row.

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

If statement doesn't execute even though condition is true

I'm at a complete loss here. I've written a relatively simple PHP script which updates a database record based on user input from a HTML form. The script contains an 'if' statement which executes based a hidden input. I know that the statement executes because the SQL query executes without a problem. The problem I'm having is that there there is another if statement within which should execute if the query object is set, but apparently it doesn't because the $message variable within is not assigned a value. I know that the query object is set because when I echo it it shows up as '1'. Below is the code block in question:
<?php
if(isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
The echoes and print_r() below the query are for debugging purposes. The code that should echo $message is above the aforementioned code block (in my script) and looks like this:
<?php if(isset($message)) {echo $message;} ?>
Also, I tried using isset() for the $r variable and also changed the condition to $r !== false but that did not make a difference. When I just echo out $message without the isset() i get the obvious " Undefined variable: message in C:\xampp\htdocs\IMS\modify.php on line 47" error. My apologies if I'm missing something glaringly obvious. I did search beforehand but all the answers were too different from my situation and my knowledge of PHP is too small for me to be able to connect dots that are that far away, if you know what I mean.
EDIT: alright, I might as well put in the entire script. It's a bit all over the place, my apologies. The $id and $table variables do show as undefined after the submit button is pressed, could that have something to do with it?
<?php
error_reporting(E_ALL);
include('config/setup.php');
$id = $_GET['id'];
$table = $_GET['table'];
if ($table == "users") {
header('Location: index.php');
exit;
}
?>
<html>
<head>
<title>Update</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="back">
Back
</div>
<div class="panel">
<?php
if(!isset($_POST['submitted'])) {
$q = "SELECT name FROM $table WHERE id = $id";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_assoc($r);
if($table == "categories"){
$type = "category";
} else if ($table == "products") {
$type = "product";
}
echo "<p>You are changing the properties of this ".$type.": ".$row['name']."</p>";
}
?>
<?php if(isset($message)) {echo $message;} ?>
<form action="modify.php" method="POST">
<label for="name">New name</label>
<input type="text" class="form-control" id="name" name="name">
<button type="submit">Submit</button>
<input type="hidden" name="submitted" value="1">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="table" value="<?php echo $table; ?>">
</form>
<?php
if(isset($_POST['submitted'])) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r !== false) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
</div>
</body>
EDIT2: Alright, I came up with a "fix" that kind of solves the problem, namely, I moved the if condition up before the echo of $message and changed the condition to isset($_POST['submitted']. This will have to do, I suppose. I guess I should read up more about the order of operations when processing submitted data and parsing PHP files in general, because I am quite confused as to why this "fix" even works...
This (conditional) statement is a false positive:
if(isset($_POST['submitted']) == 1)
What you need to do is either break them up into two separate statements:
if(isset($_POST['submitted']) && $_POST['submitted']== 1)
or just remove the ==1.
Your code is also open to a serious SQL injection. Updating a table and setting columns from user input is not safe at all.
At best, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, please note that you cannot bind a table and/or a column should you want to convert that to a prepared statement method.
Therefore the following will fail (when using a PDO prepared statement as an example):
$q = "UPDATE :table SET :name = :name WHERE id = :id;
or
$q = "UPDATE ? SET name = :name WHERE id = :id;
Read the following about this method, where that cannot be used:
Can I parameterize the table name in a prepared statement?
Can PHP PDO Statements accept the table or column name as parameter?

Check submit form input with mysqli database

When I type a code into my form I want my PHP code to check on submit that the code exists in the database and then run MySqli query. I have tried to do that but I get error Cannot use isset() on the result of an expression (you can use "null !== expression" instead) I have Googled the problem but not a single one did help me to solve or understand my problem.
FORM
<p><b>Skriv in din laddkod nedan och tryck på "Ladda"</b></p>
<form action="laddaklar.php" method="post">
<input type="text" name="laddkod"/>
<input type="submit" name="submit" value="Ladda" />
</form>
PHP
<?php
session_start();
$mysqli = NEW MySQLI ('localhost', 'root', '', 'ph');
$laddkod = isset($_POST['laddkod']) ? $_POST['laddkod'] : '';
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
if(isset($_POST['submit'] && $laddkod==$result)){
$resultSet = $mysqli->query ("UPDATE card_credit SET value= value + (select credit from card_refill WHERE refill='" . $_POST['laddkod'] . "') WHERE card_id = '" . $_SESSION['card'] . "' ");
echo "<b>Ditt kort har laddats!</b>";
}
else
{
echo "Fel laddkod";
}
The error that you're getting:
Cannot use isset() on the result of an expression
Is caused by what looks like an attempt to use an expression here:
if(isset($_POST['submit'] && $laddkod==$result)){...
You have to close the isset() properly and remove the spurious extra ):
if( isset($_POST['submit']) && $laddkod==$row['refill'] ){...
-----------------------add^ --------------------remove^
Furthermore you're not fetching any row results for the first query:
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
$row = $result->fetch_assoc(); // The value will be in the $row array
Then you appear to never execute the UPDATE query.
Additionally it is not clear where you're setting $_SESSION['card'], but you will want to make sure it is set before attempting the UPDATE query.

Taking data from a sql query in php and sending it to another php

So, i have a php page that makes a combobox by taking data from a database. After i interrogate the database i want to save the selection and send it to another php page. But, the problem is it doesn't reach it.
<form action ="sending.php" method="POST" >
<?php
$link = mysql_connect('localhost', 'root', '','printers');
mysql_select_db("printers", $link);
$query = "SELECT name_printer FROM insurers";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='users' class='dropdown-menu'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name_printer']}'>
{$row['name_printer']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<br><br>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
And the sending.php
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['users']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
var_dump( $maker);
}
?>
What it prints is string(0) "".
Your issue is with the $maker variable, it is set from an escaped $_POST['selected_text'] which if you look in the html the value is set to value="", so by var_dumping it you would not receive any output.
What you should do instead is use mysql_real_escape to escape the $makerValue rather than $_POST['selected_text'].
That way it will dump the data received from the database.
Actually you are already getting selected_text from bellow statement :
$makerValue = $_POST['users'];
So you can use bellow code directly :
$maker = mysql_real_escape_string($_POST['users']);
One more thing,
mysql_real_escape_string()
is deprecated as of PHP 5.5.0

foreach loop inserting all the checkboxes (checked and unchecked)

I have a form that generates html checkboxes using php which is shown below
<p><form name="university" action="/university_handler" method="post">
<fieldset>
<table class="table">
<thead>
<tr>
<th><span class="help-block">University Department</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php
$query = mysqli_query($db, "SELECT university_department FROM university WHERE university_id = '$university_id'")
or die ("Could not search!");
while($row = mysqli_fetch_array($query)){
$university_department = $row['university_department'];
$_SESSION['university_department'] = $university_department;
$universityDepartment = $_SESSION['university_department'];
echo "<label><input type='checkbox' name='university_department[]' value='{$universityDepartment}'>$universityDepartment</label><br><input type='text' value='' name='professor_name[{$universityDepartment}]' placeholder='Professor-Name'><input type='text' value='' name='class_name[{$universityDepartment}]' placeholder='Class-Name'>";}
?></td>
</tr>
</tbody>
</table>
<button type="submit" name="Submit"class="btn btn-info">Submit</button>
</fieldset>
</form></p>
Now when I use my university_handler to insert the values into the database all of the check boxes are inserting instead of just the ones that have been checked off. I've been trying a range of things be nothing seems to be working. Here is the handler.
<?php
session_start();
include("connect.php");
$university_id = $_SESSION['university_id'];
// check if share_form is submitted and not empty
$error_message = "";
if(is_array($_POST['university_department']) && !empty($_POST['university_department'])){
$error = array();
$universityDepartment = $_POST['university_department'];
if (count($universityDepartment)>0){
foreach (str_replace('#', '', $_POST['class_name']) as $departmentName => $stripid){
$class_name_backslash = $stripid . '/';
$class_name = mysqli_real_escape_string($db, $stripid);
print_r($class_name);
}
$query_uni = ("INSERT INTO temp_list(departmentName, class_name, professor_name) VALUE ('$departmentName','$class_name', '$professor_name')");
$q_u = mysqli_query($db, $query_uni) or die ('Error posting data');
}
}?>
I like #Martin's answer. The only thing i want to change is the $_REQUEST
When using $_REQUEST you are saying hey look at a post or get variable and use either value. So what happens if you have both a $_POST and a $_GET variable with the same name? One will be used while the other does not.
So lets use the same code in a different way.
$checkBoxName = (isset($_POST['checkBoxName']) ? $_POST['checkBoxName'] : (isset($_GET['checkBoxName']) ? $_GET['checkBoxName'] : ''));
if ($checkBoxName != '') {
//do stuff here
}
This way since you can not see post info without using something like Google Chromes developer tools, its best to do it in this order so you check what is not seen before what you can see.
Hope this helps =)
EDIT:
Based on the information you gave me, i was able to come up with a way to insert only the classes you check off. Feel free to do the change this but this should work
<?php
$departList = ($_POST['university_department'] ? $_POST['university_department'] : ($_GET['university_department'] ? $_GET['university_department'] : array()));
$classList = ($_POST['class_name'] ? $_POST['class_name'] : ($_GET['class_name'] ? $_GET['class_name'] : array()));
$profList = ($_POST['professor_name'] ? $_POST['professor_name'] : ($_GET['professor_name'] ? $_GET['professor_name'] : array()));
if (count($departList) > 0) {
foreach ($departList as $key => $val) {
$class = $classList[$val];
$professor = $profList[$val];
$query_uni = ("INSERT INTO temp_list(departmentName, class_name, professor_name) VALUE ('$val','$class', '$professor')");
$q_u = mysqli_query($db, $query_uni) or die ('Error posting data');
}
}
?>
Good Luck =)
You can use the isset function to check wether the checkbox is checked.
if (isset($_REQUEST['checkBoxName']));
{
$variable = $_REQUEST['checkBoxName'];
}
Using this method you will only get the checkbox that has a value.
Hope this helps

Categories