Wrong part of if statement being executed - php

When I delete a record from table, I have 8 columns in the table and if more than 8 is entered it must be showed that nothing was deleted. However every number that I give, I get the same response "deleted successfully". This is my code:
$query = "DELETE FROM `order` WHERE orderId = '$_POST[id]'" ;
$result = mysql_query($query);
if(! $result )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}

$result will be a valid result, even when your query won't affect any rows. Use mysql_affected_rows() to check if you deleted anything.
$result = mysql_query($query);
if( mysql_affected_rows() == 0 )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
side note: the mysql_* functions are deprecated. Don't use them to write new code, especially when you are learning. Use mysqli_*or PDO instead.

You can use mysql_affected_rows
$query = "DELETE FROM `order` WHERE orderId = {$_POST[id]}" ;
mysql_query($query);
if(0 == mysql_affected_rows()){
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}else{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}

You are testing if your query ran successfully. It can be successful if it deletes one row or if it deletes none.
Use mysql_affected_rows to determine if you've deleted any rows.
(You'd be better moving to a more modern API though)

Related

Problems With Double-Entry with update

I'm trying to set up an update query to add the last entry with the new entry but my new entry keeps doubling.
I keep looking for error but everything seems ok in not sure why the value of sum keeps doubling.
$sum ='1';
$sql = "update table set old = old +'$sum' where id='1'";
$query=mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo '<script type="text/javascript">alert("A ok");</script>';
} else {
echo "Bigo Problem: " . $con->error;
}
Try This
$sum =1;
$sql = "update table set old = old +'$sum' where id=1";
if ($con->query($sql) == TRUE) {
echo '<script type="text/javascript">
alert ("A ok");
</script>';
} else {
echo "Bigo Problem: " . $con->error;
}
This is the reason for doubling sum because query exected twice by your code.
$query=mysqli_query($con,$sql);
if ($con->query($sql) === TRUE)
Remove one line and code will work fine.
issue with below two lines.
$query=mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
Above two line make two entry.
The problem is that mysqli_query($con,$sql) executes your query....and then $con->query($sql) also executes your query.
So you are running the same query twice from two different commands.
You can just remove $query=mysqli_query($con,$sql); - it isn't needed.

php mysql pdo resultset with one row not entering foreach

Simple Login Form Using PDO .The Output of echos works fine .Enters inside the else case But does not go inside the foreach loop.
The output of var_dump gives this .
echo output
1rows SelectedEntered successfull loop
var_dump output
object(PDOStatement)[3] public 'queryString' => string 'select *
from tour_login where username='admin' and password='admin' and
status=1' (length=81)
if(isset($_POST['login']))
{
$un=$_POST['un'];
$pass=$_POST['pass'];
$res=DB::getInstance()->query("select * from tour_login where username='$un' and password='$pass' and status=1");
$num_rows = $res->fetchColumn();
echo $num_rows."rows Selected";
if($num_rows<=0)
{ echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
else
{
echo "Entered successfull loop";
foreach ($res as $row) {
echo "Entered successfull for loop";
if($row['type']==0)
{
$_SESSION['admn']=$un;
echo "<script>alert('welcome admin...');document.location='adminhome.php';</script>";
}
else
{
$_SESSION['usr']=$un;
echo "<script>alert('welcome user...');document.location='userhome.php';</script>";
}
}
}
}
What I am not understanding is why foreach is not working with number of rows showing one.New to Php.I found alternative of using mysql_num_rows() in pdo in this StackOVerflow Question
https://stackoverflow.com/questions/11305230/alternative-for-mysql-num-rows-using-pdo
Your first problem is that, being a novice, you just snatched one line from the code you found, having no idea what does it do. This line would never return number of rows found, yet this line is responsible for your confusion, as it fetches all the data you selected, leaving nothing for the foreach loop. Though you don't need the latter as well.
Your second problem is that you are under a very common delusion, thinking you need number of returned rows at all. In fact, you don't actually need it.
Your third problem is that you ought to be using prepared statements but you aren't.
The code you need is
$sql = "select * from tour_login where username=? and password=? and status=1";
$res = DB::getInstance()->query($sql);
$res->execute(array($un, $pass));
$row = $res->fetch();
if(!$row) {
echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
and so on. Just remove useless foreach loop and you're set.

mysql_fetch_array() not spiting anything

Here is my code:
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
$conn=mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name'],$conn);
$exec_query =mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
The Problem is that I am not getting anything in $row I cant get into the while loop, nothing shows up when I try to echo the value of $row, No error Nothing. Can you help me to find a problem in my code ?
Ps : The database is their. I have checked for the query for the corresponding value of $campagin_id. and also when i tried to echo $exec_query it echoed this : Resource id #8
PPS : The database have more than 7 record for each id so it doesn't matter if I call mysql_fetch_array($exec_query) more than once before going in to the while loop. and for the $campagin_id in the session their are many records present in the database.
You have written $row=mysql_fetch_array($exec_query) and then you are echoing something. and you are using the same in while.
Instead of:
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
Use this (as per my knowledge you should not use $row=mysql_fetch_array() once you have used before while):
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
If the query returns Resource id #8 then that means it was successful - ie there were no errors. There were probably no rows returned by that query, so no rows in your table that match the given campagin_id.
You are also calling mysql_fetch_array() twice separately, you shouldn't do that because your while loop will skip the first row because calling this moves the pointer in the result set forward by one.
Also you can't echo an array as you are trying to, if you want to see the contents of an array use print_r() or var_dump().
I suggest adding some code to handle no rows found:
if($exec_query && mysql_num_rows($exec_query) > 0)
{
while ($row=mysql_fetch_array($exec_query)){
echo "Row: " . print_r($row, true);
}
}
else
{
echo 'None found';
}
Try this code.
<?
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name']);
$exec_query =mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_assoc($exec_query)) {
echo "<br/> row = <pre>".print_r($row)."</pre><br/>";
}
?>

MySql if statment not working

In my Details table, when the complete field is '0' I want a certain image to appear when it is '1' I want a different image to appear. At the moment only the second image is showing (when complete field is 1)
This is the code I am using:
$id = $_SESSION['user_id'];
$isFinished= mysql_query("SELECT complete From details where user_id = $id") ?>
<p> <img src='<?php if($isFinished) echo "correct.png"; else echo "incorrect.png"; ?>' /><a href="details.php">Details</p>
Any ideas would be great!
The WHERE clause of your query is specifying only select records where complete = '1'
So you'll only get 1 back in the results.
You should remove that from the WHERE clause completely and let your php IF statement decide whether complete = '1'
the function
function getOne($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("db: ".mysql_error()." in ".$query);
return FALSE;
}
if ($row = mysql_fetch_row($res)) {
return $row[0];
}
}
the code
$sql = "SELECT complete From details where user_id = ".intval($_SESSION['user_id']);
$isFinished = getOne($sql);
?>
<p>
<img src='<?php if($isFinished): ?>correct.png<? else: ?>incorrect.png<? endif ?>' />
Details
</p>
Your SQL statement only selects entries with complete='1'.
You should remove the "and complete='1'" from your statement.
Edite:
ALso as mentioned above your if statement only check if your query returned something or got an error.
It should be
if($isFinished['complete'] == '1') {echo "correct.png";}else{echo "correcy.png";}
It should be something like this:
$id = $_SESSION['user_id'];
$result= mysql_query("SELECT complete From details where user_id = $id and complete='1'") ?>
$row = mysql_fetch_array( $result );
<p>
<?php if($row['complete']): ?>
<img src="correct.png"/>
<?php else: ?>
<img src="incorrect.png"/>
<?php endif; ?>
<a href="details.php">
Details</a>
</p>
The mysql_query function returns false only when the query is invalid. It does not return false if there are zero rows.
You should use the mysql_num_rows function to determine if there was a row or alternatively use the mysql_fetch_* functions to fetch the value of complete.
Example 1 (Similar to your original (unedited) question):
$result = mysql_query("SELECT 1 From details where user_id = $id where complete = 1");
$isFinished = mysql_num_rows($result);
Example 2 (Alternative):
$result = mysql_query("SELECT complete From details where user_id = $id");
$record = mysql_fetch_assoc($result);
$isFinished = $record['complete'];
Is this the whole code?
In this case $isFinished is not the content retreived from db: mysql_query returns false if query is wrong otherwise an object where you can fetch the results.
In this case if($isFinished) is always true as the query is correct!
you miss the fetch part ater query execution!
http://php.net/manual/en/function.mysql-query.php
For example:
$id = $_SESSION['user_id'];
$result = mysql_query("SELECT complete From details where user_id = $id");
$isFinished= mysql_num_rows($result);
<p> <img src='<?php if($isFinished) echo "correct.png"; else echo "incorrect.png"; ?>' /><a href="details.php">Details</p>
This way if query returns one ore more rows then $isFinished is 1 or more otherwise $isFinished is 0. Your if - else should then work properly
Note i did not change the your original SQL, change it if you need.

PHP - $GET and delete from MySQL

I have an a href which looks like that: Delete
And file delete-news.php is as follow:
<?php
if(isset($_GET["?deleteID='.$id."]))
{
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
But it is returning GET NOT SET. What I'm doing wrong?
Use this, and for god's sake escape your inputs.
if(isset($_GET['deleteID'])) {
$result = mysql_query("DELETE FROM `news` WHERE id='".mysql_real_escape_string($_GET['deleteID']). "'");
echo mysql_error();
if($result)
echo "succces";
} else {
echo 'GET NOT SET';
}
$_GET will have each element of the GET variables already broken down, so no need to include the URL data. So, in your example, the link ?deleteID=123 would produce $_GET['deleteID'].
Try using that, but also remember to sanitize the values you receive in from URLs. If it's going to be a numeric value, I suggest casting it:
$deleteID = (int)$_GET['deleteID'];
Please also note that changes to the system should only happen via POST, and never GET. Otherwise (for example), you might get a spidering bot that deletes your whole site. See this post for more references:
https://stackoverflow.com/questions/679013/get-vs-post-best-practices
You need to check $_GET for just deleteID. Later, reference it as $_GET['deleteID']. Also, call mysql_real_escape_string() on $_GET['deleteID'] to retrieve your query parameter $id.
if(isset($_GET["deleteID"]))
{
$id = mysql_real_escape_string($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
Try this instead:
<?php
if(isset($_GET['deleteID']))
{
$id = intval($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result) echo "succces";
} else {
echo "GET NOT SET";
}
?>
Note that I'm making the given deleteID into an int, meaning that values other than some form of number will become 0.
Also, you can't wrap a table- and/or column name with ' - backticks are the way to go!
<?php
if(isset($_GET["deleteID"]))
{
$id = ($_GET['deleteID']);
$result = mysql_query("DELETE FROM news WHERE id='".mysql_real_escape_string($id)."'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
is correct one
You obtain GET NO SET, because the $_GET associative array does not contain ?deleteID='.$id.
In order for you to obtain the id, you need to so something like this:
$id = $_GET['deleteID'];
Also
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
That is very unsafe as it allows SQL injections. Instead, do:
$query = sprintf("DELETE * FROM news WHERE id=%d",
mysql_real_escape_string($id),
$result = mysql_query($query);
I hope this helped.

Categories