This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows
Related
/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}
I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";
I have the following code.
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus=$HealthStatus";
$result = mysql_query($query);
echo $HealthStatus;
if($result = false)
{
//do something
}
else
{
//print value already exists
}
I don't get any error or warning when the code is executed. But, even if $HealthStatus exists in database, the if part gets executed. When I give echo $HealthStatus, the value fetched is printed correctly.
I have tried using if(!$result). That doesn't work either. Can someone help me.
You have to use mysql_num_rows to know if the query returned any rows, eg:-
if($result && mysql_num_rows($result))
{
// a row exists
}
else
{
// do something
}
also if HealthStatus is a string it needs to be enclosed in quotes eg:-
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus='".$HealthStatus."'";
$result = mysql_query($query);
if($result && mysql_num_rows($result))
{
// a row exists
$row=mysql_fetch_array($result);
echo "Health status was ".$row["HealthStatus"];
}
else
{
// do something
echo "There were no rows found";
}
To understand how much rows were received use mysql_num_rows function.
if(mysql_num_rows($result) > 0) {
} else {
}
Also, you have error in your if:
if($result = false)
{
//do something
}
else
{
//print value already exists
}
You assign false to $result in your if statement.
You have to use if($result == false).
To avoid such mistakes you can change order:
if(false == $result)
This will work, but this:
if(false = $result)
Will cause error.
Hope, this will help.
I am dying here :-) Please help out!
The following query gets different messages for different users from the same table based on current time.
$message = mysql_query("SELECT * FROM `table`
WHERE `Scheduled` <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 MINUTE)
AND `Status` != 'published'");
/** Kill db connection and exit script if no results are found **/
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
{
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}
}
This only echos the first account, please help I have a headache. I have run this on the db directly and it works fine. I believe I am messing up in php
I think you are getting non associative array. If you wanna assoc. array, you have to change it :
while ($row = mysql_fetch_array($message))
to
while ($row = mysql_fetch_assoc($message))
//you have made a drastic mistake in your code check now it will work
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}
I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php