PHP if/else statement acting weird - php

I'm relativity new to php and just testing out some code. The odd thing is that the code both does/doesn't work. The code should check a MySQLi database to determine the state of the check box and then apply that state to the checkbox. What the code currently does is designate the checkbox state based solely off the value of the if condition, regardless of the MySQLi database values.
Here is the code for the html page, it's the if statement near the bottom that's causing issues;
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$results = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
$sql_2 = mysqli_query($conn, "SELECT state FROM test2 WHERE id = '0'") or die('Error getting data.');
if ($sql_2 == "0") {
echo "checked";
} else {
echo " ";
}
mysqli_close($conn);
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1" checked> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset<br>
</body>
</html>
The odd thing about this code is that the if ($sql_2 == "0") results in the checkbox remaining unchecked, but changing the 0 to a 1, if ($sql_2 == "1") results in the checkbox remaining checked. Both results are regardless of what the database shows.
I know all the other bits of code work, because when I check the checkbox and submit, it updates the database and displays it correctly (the reverse is also true).
If anyone knows why if ($sql_2 == "0") is not working, please let me know. I've even checked other stack overflow postings, and as far as I can tell, everything should be coded properly.
Edit:
I should have stated that in the above question, changing the = to == or reversing the order doesn't fix the problem. The if statement still only returns the else statement.
I've done additional research and think that the issue is related to the use of mysqli_query to retrieve the data, as it should likely be mysqli_fetch_row.

if ($sql_2 = "0") will make the value of $sql2 to '0' and this condition will be always true
change it to
if ($sql_2 == "0")
to prevent the accidental assignment you can do like below
if ("0"==$sql_2)

ISSUE FIXED
The solution was to add a mysqli_data_seek() to the php, below is the working code.
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$result_1 = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($result_1, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
$query_1 = "SELECT state, id FROM test2 ORDER BY id";
$sql_3 = mysqli_query($conn, $query_1) or die('Error getting data.');
if ($result_2 = $sql_3) {
mysqli_data_seek($result_2, 0);
$row_1 = mysqli_fetch_row($result_2);
}
if ($result_3 = $sql_3) {
mysqli_data_seek($result_3, 1);
$row_2 = mysqli_fetch_row($result_3);
}
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
if ($row_1[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1"
<?php
if ($row_2[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset
<br>
<?php
mysqli_close($conn);
?>
</body>
</html>

Related

Search multiple Criteria - And/or search in PHP

Not sure what I am doing wrong here. I would like to create a search that allows the user to do an and or search.
However when I use the below code, if I type in Brown as Colour1 it will return all results, same as post code.
The goal is to allow the user to search multiple fields to return a match. So Colour1 and Postcode
<html>
<head>
<title> Logo Search</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width: 250px;
text-align: left;
}
</style>
</head>
<body>
<h1> National Logo Search</h1>
<form method="post" action="singlesearch2.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%')
or
('Colour2' like '%$criteria2%')
or
('PostCode' = '%$criteria3%')
or
('Suburb' like '%$criteria4%')
LIMIT 0,5";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>
I can get it to work correctly when I use a dropdown list to select the criteria however I would like them to have multiple options to filter results.
<form method="post" action="multisearch.php">
<input type="hidden" name="submitted" value="true"/>
<label>Search Category:
<select name="category">
<option value="Colour1">Main Colour</option>
<option value="Colour2">Secondary Colour</option>
<option value="PostCode">Post Code</option>
</select>
<label>Search Criteria: <input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
echo "connected " ;
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE $category LIKE '%$criteria%'";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
In general you run your query with AND condition because it has criteria and you have it means that you have to show value by matching each criteria with receptive column. but it also depends on users or client how they want to show their field.
In short it doesn't have any rule how to show.
Played around with it for a bit and found the answer. I needed to define the criteria. see below code
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')

A simple operation but it giving an error I want to update each id

It is simple but I am not getting values of radio buttons for updation when I press submit.
It is giving an error in foreach statement like :Warning: Invalid argument supplied for foreach() Please say how to get the values of radio button after pressing submit button,
here I am updating the status of state .
<?php
include("db.php");
?>
<html>
<body>
<?php
$state=$_POST['state'];
if(isset($_POST['submit']))
{
$result1 = mysql_query("select state,id,status from states ");
while($rr1=mysql_fetch_array($result1))
{
//getting values of radio buttons
$myval=$rr1['id'];
echo $myval;
$val=$_POST['yes.$rr1["id"]'];
echo $val;
$val1=$val.$myval;
$vall=yes.$rr1['id'];
foreach($vall as $values)
{
echo $values;
$update=mysql_query("UPDATE states SET status='". $values."'
WHERE id='$myval' ");
}
}
}
echo "ok";
?>
<form action="" name="form" id="form" method="post" >
<?php
//session_start();
include("db.php");
$result = mysql_query("select state,id,status from states ");
while($info1=mysql_fetch_assoc( $result))
{
echo $info1['city'];
echo "<br>";
/*echo "<br>";
echo "company Name:".$info1['company_name'];
echo "<br>";
echo "salary:".$info1['maxsalary'];
echo "<br>";
//echo $info1['company_name'];*/
?>
<label><?php echo $info1['state']; ?></label>
<input type="radio" <?php if($info1['status']=="yes"){ echo
"checked='checked'"; } ?> name="yes.<?php echo $info1[ 'id']; ?>[]"
value="yes">Yes
<input type="radio" <?php if($info1['status']=="no"){ echo
"checked='checked'"; } ?> name="yes.<?php echo $info1[ 'id']; ?>[]"
value="no">no
<br/>
<?php } ?>
<br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
I think you need to write
$vall=yes.$rr1['id'];
to
$vall="yes".$rr1['id'];
Thanks

Inserting SQL Database values in HTML update form

I'm trying to make a form that will allow a user to edit records in the database.
My main.php is a table where the user can click on a record to edit / delete:
echo "<td>".$row["fname"].", ".$row["first_name"]."</center></td>";
echo "<td><center>".$row["gender"]."</center></td>";
echo "<td><center>".$row["city"]."</center></td>";
echo "<td><center>".$row["extra"]."</center></td>";
echo '<td><center><img src="edit_icon.png"/><center></td>';
echo '<td><center><img src="delete.gif"/><center></td>';
echo "</tr>";
}
?>
<input type="hidden" name="p_ID" value="<?php echo $row["p_ID"]?>"></input>
<input type="hidden" name="lname" value="<?php echo $row["lname"]?>"></input>
etc..
When the user clicks the edit icon, it redirects to the form page where I need the values ($row['fname']) to show up in their respective fields. I've tried suggested solutions but I still don't know how to accomplish this correctly. I keep getting errors. This is what I've tried with my form.php
#$submit=$_POST['submit'];
#$lname=$_GET['lname'];
#$gender=$_GET['gender'];
#$city=$_GET['city'];
#$extra=$_GET['extra'];
?>
Last name <input type="text" name="lname" value= <?php echo $lname ?>><br><br>
Gender <input type="radio" name="gender" value="M" <?php if($gender=="M") {echo "checked";} else {echo " ";} ?>/>M
<input type="radio" name="gender" value="F" <?php if($gender=="F") {echo "checked";} else {echo " ";} ?>/>F<br><br>
City <select name="city">
<option value="x">Select</option>
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
$num_results=mysql_num_rows($result);
mysql_close($db);
for ($i=0;$i<$num_results;$i++)
{
$row=mysql_fetch_array($result);
echo"<option value='".$row['city_id']."'", $row['city_id']==$row['city_ID']? " selected='selected'" : '',">".$row['city']."</option>";
}
?>
</select><br><br>
Extra <input type="checkbox" name="extra" value="yes" <?php if($extra=="yes") {echo "checked";} else {echo " ";} ?>/><br><br>
And I'm not really concerned with any SQL injections or anything right now, I just need this working. I'd be grateful for any help!
Errors: Undefined index for everything
You are closing the connection before mysql_query is used in mysql_fetch_array.
You are trying to fetch the rows incorrectly.
mysql_close isn't needed unless you have a lot of processing after the query because the connection is closed after the script has finished running anyway.
Also, declare your variables like this to remove the undefined index errors:
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
Note: this also protects against sql injection but mysql_real_escape_string() will only work after you connect.
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
//other vars here
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['city_id']."'>".$row['city']."</option>";
}
mysql_close(); // now you can close the connection
?>
What you need is form submission check. Here is the general form of a single-page update script:
<?php
if(isset($_POST['submit'])) {
// Form was submitted, process it and display message
exit(); // Prevent form from being displayed again
}
?>
<!doctype html>
<html>
<body>
<form method="POST" action="form.php">
<!-- fields -->
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

php form submit - Q2

i am sorry for the dummy question. Here is my simple PHP form with two SQL tables and with the ADD submit button I would like to move people from Test1 to Test2. Many thing are fine:( only the submit button does't work therefore no feedback from Test2 table.
Revised: Submit now works great
Q2 - still don't get the checkboxs to work:( - please
Could somebody show me how to track back such an error like this please?
<?php include("db_connect.php");?>
<html>
<head></head>
<body>
<form method="post" action="moving.php">
<table border="1">
<tr>
<td>
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1)) {
?>
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php } ?>
</td>
<td><input type="submit" id="add" name="add" value="Add" /></td>
<td>
<?php
$rigth='SELECT * FROM test2,test1 WHERE test2.collect=test1.id ORDER BY test1.name ASC';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2)) {
echo $resultb['id'] ;
echo "<br />";
}
?>
</td>
</tr>
</table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($i=0;$i<$count;$i++) {
$add_id = $checkbox[$i];
if ($add_id=='1') {
$sql = "INSERT INTO test2 (status, collect) VALUES(1, 1)";
$result = mysql_query($sql);
}
}
// if successful redirect to delete_multiple.php
if ($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=moving.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>
thanks:) from a beginner
where does $count come from?
Try using count($_POST['checkbox']) instead on your INSERT statement. Then you can iterate over the checkboxes using:
for ($c = 0; $c < count($_POST['checkbox']); $c++){
$checkbox = $_POST['checkbox'][$c];
...INSERT action...
}
In the sample code, you store the statement in a variable named $rigth, but you (try to) execute a statement stored in a variable named $right.
There are a couple things you can do to catch errors.
Try static code analysis; some tools can tell you if a variable is used only once (an indication it may be a typo).
Handle errors. Some functions return a special value if there's an error (False is a common one); for these functions, there is usually a related function that will return error information. Some functions will throw an exception; catch them where they can be appropriately taken care of. System error messages shouldn't be displayed to non-admin users so you don't disclose too much information.
Use an interactive debugger. For example, install the Xdebug extension on your development server (you do use a dev server, right?) and use an Xdebug compatible debugger.
the solution - not nice but it works - thanks for all the comments and help!!!
<?php include("db_connect.php");?>
<html>
<head>
</head>
<body>
<form method="post" action="test.php">
New:
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1))
{
?>
<input name="checkbox_add[]" type="checkbox" id="checkbox_add[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php
}
?>
</td> <td><input type="submit" id="add" name="add" value="Add" /><br /><input type="submit" id="delete" name="delete" value="Del" /></td><td>
<?php
$right='SELECT test2.id, test1.name FROM test2, test1 WHERE test1.id=test2.collect AND test2.status=1';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2))
{
?>
<input name="checkbox_del[]" type="checkbox" id="checkbox_del[]" value="<?php echo $resultb['id']; ?>"/>, <?php echo $resultb['id']; ?>, <? echo $resultb['name']; ?>
<br />
<?php
}
?>
</td></tr></table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($c = 0; $c < count($_POST['checkbox_add']); $c++){
$checkbox_add = $_POST['checkbox_add'][$c];
$sql = "INSERT INTO test2 (status, collect) VALUES(1, ".$checkbox_add.")";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['delete'])) {
for ($c = 0; $c < count($_POST['checkbox_del']); $c++){
$checkbox_del = $_POST['checkbox_del'][$c];
echo date("Y-m-d");
$sql = "UPDATE test2 SET status='2', log='".date('Y-m-d')."' Where id=".$checkbox_del;
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['new'])) {
$sql = "INSERT INTO test1 (status, name) VALUES(1, '".$_POST['newitem']."')";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories