php code In If Else Condition Not Working Properly - php

table name -- breaking_news
field name -- status
I have created a single page and passes id from link click.
Now I check if status not empty and status equal to Inactive
then update status = Active Else update status Inactive
but it is not working properly.
It Only Works For If Condition.
The ELSE Condition of Code is Not Working . plz suggest me how to write in if else properly...
<td><img src="img/active.png" width="24" height="24" border="0" title="Active" /></td>
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!empty($row) && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>

Try this code
">
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!$row && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>
you have just to ask if $row was have more or not, be cause mysql_fetch_assocreturn false if it's empty look to this manual : mysql_fetch_assoc PHP
you have just do not use empty()

Or like that :
if($row = mysql_fetch_assoc($result))
{
if($row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}

If you have not found a row, there is nothing to update...
You may wish to do something like this:
<?php
if (!empty($row)) {
if ($row['status'] == 'Inactive') {
//update to active
}
else if ($row['status'] == 'Active') {
//update to inactive
}
}
also you've got a typo in the second call to $_GET array: $_GET['status_inactive']. You should be updating the same row but with different status value.
EDIT
#toto21 I don't have enough reputation to comment on your answers but no, your answer is wrong. As I mentioned at the top - if there is no row fetched then there is nothing in the db for you to update, so your else statement makes no sense.

Related

php: UPDATE SET function not updating table

I have a function to update a table but it does not work. My php error log does not report anything being wrong either so I am a bit stuck.
Here is the code:
if (count($errors) == 0) {
$query = "UPDATE wotd SET spanish='$spanish', english='$english', sex='$sex', example_es='$example_es', example_en='$example_en', description='$description' WHERE id=$wotd_id";
$_SESSION['message'] = "WORD updated successfully";
header('location: words.php');
exit(0);
My code was incomplete and therefore not posting the data to the database.
I needed to add another line below $query = "INSERT..."
This is my updated code:
if (count($errors) == 0) {
$query = "UPDATE wotd SET spanish='$spanish', english='$english', sex='$sex', example_es='$example_es', example_en='$example_en', description='$description' WHERE id=$wotd_id";
mysqli_query($conn, $query);
$_SESSION['message'] = "WORD updated successfully";
header('location: words.php');
exit(0);
}

Have php switch column value to either 1 or 0

I'm learning PHP and getting a little frustrated. I have an html form that is sending data to another php page $_POST["id"];.
On a 2nd php page I'm trying have the "available" column in the table either switch to 1 or 0. If it's already 1 go to 0, and if it's 0 go to 1.
I know my code is probably completely wrong and messy but please excuse me as I'm still learning.
if ($row["available"] == 1) {
//$row["available"] = 0;
$sql = "UPDATE check_in_out SET available=0 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
} else {
//$row["available"] = 1;
$sql = "UPDATE check_in_out SET available=1 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
If you want to toggle the value you can use this:
$sql = "UPDATE check_in_out SET available = (1-available) WHERE id='".$_POST["id"]."'";
or
$sql = "UPDATE check_in_out SET available = IF(available = 0, 1, 0) WHERE id='".$_POST["id"]."'";

PHP If statement returning early(amateur)

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';";

how to prevent same record to be inserted twice in mysql using php

The following is my code that I have written for not inserting same data
I would like if the record exist in mysql then it should show me error message that the record already exist the else part should insert record to database but it not working
can any one help me plz
the help would be highly appreciated
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you did mistake here.
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
just add mysql_query like
$check=mysql_query("SELECT * FROM contacts WHERE office_name = '$officeName'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
or you can also use like
$name=$_POST['username'];
$q="select * from login where name='$name' ";
$rs=mysql_query($q);
if(mysql_fetch_row($rs)>0)
{
echo "already exist";
}
else
{
$msg="done";
}
Add the ON Duplicate KEY Update. This way you don't need to check if the record already exists, which means you don't need an extra select query just to check. If it exists, nothing happens.
INSERT INTO contacts (office_name, contact_no, digital_no, mobile_no)
VALUES ('$contactName','$contactNo','$digitalNo','$mobileNo')
ON DUPLICATE KEY UPDATE office_name = office_name
And set the office_name to be the primary key or a unique index.
There is missing one step, your first query is not executed, please try this:-
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check= mysql_query("SELECT * FROM contacts WHERE office_name = '{$officeName}'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you can handle it from database side. write a stored procedure such a way that first check weather the record is in database or not if exist then ignore it and get back the text "Record already exist", if not exist then insert it to table. use conditional statements in mysql.

No results returned for elseif PHP query

I have a database with a 'status' column which either reads 'active' or 'inactive'.
I'd like to return different text depending on whether the status is 'active' or 'inactive', and I'm using if... and elseif... for this.
If the status is 'active', the message is displaying perfectly. This also prompts the database to update the status field to 'inactive' - again, this is working perfectly.
But if I reload the page, using a key for which I know the status is 'inactive', nothing displays.
<?php
if (isset($_GET['key'])) {
$key = $_GET['key'];
include("db.php");
$download_query="SELECT * FROM sales WHERE key='$key'";
$download_result=#mysql_query($download_query);
$download_row=#mysql_fetch_array($download_result, MYSQL_ASSOC);
$productid=$download_row['productid'];
$datecreated=$download_row['datecreated'];
$dateaccessed=$download_row['dateaccessed'];
$status=$download_row['status'];
if ($status=="active") {
$download_updatestatus_query="UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result=#mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
}
else {
echo "Sorry, no key provided.";
}
?>
You have an extra } after your elseif. try:
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
else {
You suppose to make sure that mysql_query is not false and contains some results by running mysql_num_rows before you start fetching data.
Also passing $_GET value to MySQL Query without validation is very bad idea.
if (isset($_GET['key']))
{
//You have to make sure that provided value is safe to use in mysql query
$key = mysql_real_escape_string($_GET['key']);
include("db.php");
$download_query = "SELECT * FROM sales WHERE key='$key'";
$download_result = mysql_query($download_query);
// Check result
if (!$download_result)
die('Invalid query: ' . mysql_error());
if($download_result && mysql_num_rows($download_result) > 0)
{
$download_row = mysql_fetch_assoc($download_result);
$productid = $download_row['productid'];
$datecreated = $download_row['datecreated'];
$dateaccessed = $download_row['dateaccessed'];
$status = $download_row['status'];
if ($status == "active")
{
$download_updatestatus_query = "UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result = mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status == "inactive")
{
echo "You may have downloaded this before.";
}
}
else
{
echo 'No results found';
}
}
else
{
echo "Sorry, no key provided.";
}

Categories