Issue with If Statement not working properly - php

I have an issue with an if logic statement that I cant seem to figure out and am looking for someone wiser than me to point out the error of my ways.
Below is my code:
$sql = "select count(id) from tempaddress where postcode='".$values['PostCode']."'";
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
print_r($data);
if ($data > 0)
{
//Redirect to Address Selection Page
$cid=$keys['CompanyId'];
header("Location: UpdateAddress_edit.php?editid1=".$cid);
exit();
}
else echo "<script>alert('No Addresses Found. Please Contact Administrator')</script>";
What this is supposed to do is look up how many results are found and if the answer is >0 then it takes it to next page, if not it gives you a popup message.
The count function works, but for some reason, even if the result is 0, it still takes the process to next page, see here http://prntscr.com/58949d, I have put a false post code in, and it should say, no!
Can anyone see what is going wrong, or point out a way to use if record exists then {}?
I am using PHP with MS Access.

Firstly, alias your expression:
$sql = "select count(id) as addressCount from tempaddress where postcode='".$values['PostCode']."'";
Then use it in the if statement
if ($data['addressCount'] > 0){
...
}
else{
}

try if($data[0] > 0 )since you're fetching as array

It should be like -
if ($data['Expr1000'] > 0)

Related

Search mySQL table for user and return true or false to $result?

What I've been trying to do for several hours now is simply check the column 'user' of a table 'nonpersonal' to match my variable '$recipient'.
I thought there must be a much easier way than selecting the whole column 'user', putting it through a while loop with fetch_assoc() and only then check if there is a 'user' that matches '$recipient'.
If yes, please tell me! :) If not, what would be the most efficient way? I tried in_array(), e.g., but couldn't get it to work. I guess I'm missing the basic understanding of how the query($sql) fills $result, which I tried to find out as well..
$sql = "SELECT user FROM nonpersonal WHERE user LIKE '$recipient'";
$result = $conn->query($sql);
if($recipient == $result)) {
echo "<br> This recipient does exist."
} else {
echo "<br> This recipient does not exist. Try again.<br>";
}
Thank you very much in advance!
Perform an exact query... LIKE is for partial or inexact matches.
$sql = "SELECT user FROM nonpersonal WHERE user = '$recipient'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
echo 'Exists!';
}
Also please be sure you have escaped $recipient to ensure you do not allow SQL injection, see mysqli::real_escape_string

No output from mysql query in PHP

I am troubleshooting this query that I was previously trying to use to count rows but now I have discovered that 0 rows are being found in the database even though they exist. I have checked previous queries I have used and they work and look the same. The $db_conx definitely works to connect to the database as I am using it on other web pages. Does any one have any suggestions? Thanks
$result =("SELECT * FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if (rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You are missing an important step to select something from the database and that is what are you trying to select. And, you are also missing the $ in the rows.
$result =("SELECT something FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if ($rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You edited your original post https://stackoverflow.com/revisions/33307758/1
being SELECT FROM Request
You have selected "nothing" from your query
SELECT FROM ...
Read the manual on SELECT:
https://dev.mysql.com/doc/refman/5.0/en/select.html
and this if (rows < 1) { - rows is treated as a constant instead of a variable.
Error reporting would have told you that if it was setup to catch and display on your system.
if ($rows < 1) {
and make sure you are successfully connected to your db using the same MySQL API as your query.
Check for errors on your query
http://php.net/manual/en/mysqli.error.php
Look into using a prepared statement also.
https://en.wikipedia.org/wiki/Prepared_statement
Nota:
You will also need to escape your data should it be coming from user input at one point.
I.e.:
$var = $_POST['var'];
and if $_POST['var'] is equivalent to joey's bistro.
MySQL will see that as WHERE user2='joey's bistro' if it were passed as a variable in the query WHERE user2='$var' resulting in a syntax error.
Escaping it will render it as joey\'s bistro being valid syntax.
$var = mysqli_real_escape_string($db_conx,$_POST['var']);
This would be beneficial for just that as well as helping to protect against an SQL injection.
https://en.wikipedia.org/wiki/SQL_injection

Check if $_REQUEST url exists in database

I'm using $id = intval( $_REQUEST['id'] ); , to get ID of the news/posts on my website, and the link to the news is article.php?id=XXX. So when someone type ?id=1 and there's nothing it's empty, no posts, it should go to index page (index.php) instead showing blank page. Is it possible? I've tried via isset something but it didn't worked. Can anyone help me with this, please.
if($ArticleSQL = $mysqli->query("SELECT * FROM articles WHERE id='$id' ")){
...
}
You can check the number of results with $ArticleSQL->num_rows.
So your code will now be:
$ArticleSQL = $mysqli->query("SELECT * FROM articles WHERE id='$id' ");
if($ArticleSQL->num_rows > 0) {
$article = $ArticleSQL->fetch_array();
//show the article here
} else {
//redirection:
header("Location: index.php");
}
You need to check if the query found anything. Your code simply checks if the query succeeded. A query which returns no rows is NOT a failure. It's a perfectly valid result set that happens to have no rows in it.
$result = $mysqli->query(...);
if ($result->num_rows > 0) { ... found something ... }

Checking if user already has account with PHP & ORACLE

I'm trying to apply the finishing touches on a register form. I want to check if the user already has an account, based on his e-mail address. However, the PHP won't help me out. Here is the main part of my code.
$s = oci_parse($conn, "SELECT * FROM users WHERE mail='&mail'");
oci_execute($s);
$rows = 0;
while (oci_fetch($s))
{
$rows ++ ;
}
echo $rows; -> this echos all the time 0 even if I have 10+ registered users with same email
if($rows > 0)
{
//has account
}
else{
doesn't have account, inserting into DB
}
It seems like the value of $rows is always 0, no matter what I Do. I also tried with
SELECT COUNT(*) FROM users WHERE mail='$mail'
But i was unable to pass the correct value to the $rows variable.
Everything else works fine in my php code.
Thanks in advance
The error comes from the sql statement you have written &mail insted of $mail.
And by the way to count your rows you can use the function oci_num_rows($s) with this function you dont have to use the while loop

PHP data retrieving problem in database

Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.

Categories