PHP mySQL 404 function - php

The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.

Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.

I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};

Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.

Related

php if statement for mysql query result (check if query returned anything)

I'm getting a bug.. and I'm thinking it might be because of this code:
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
if($id = $r->fetch_assoc()["id"]){
echo 'greg!!!<br>';
}
I'm just trying to echo 'greg!!!' if the query "select id from Posts where post='$post'" returns anything. I'm finding that sometimes this works and sometimes it doesn't... so not really sure. Maybe it's a quotes issue?... but I would think that the addslashes method would take care of that
$r->fetch_assoc()["id"]
I think this will not work, because $r->fetch_assoc() is not an array yet. It should be like:
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
$fetch = $r->fetch_assoc();
if($id = $fetch["id"]){
echo 'greg!!!<br>';
}
And it will get in if if SQL query returns anything. You can always check your array with f.ex.:
print_r($fetch);
Or use $r->num_rows to count how many rows have been returned.
You could use rowCount()if PDO, or num_rows if MySQLi to check if there were any rows returned.
// PDO
if($r->rowCount() > 0){echo "greg";}
// MySQLi
if($r->num_rows > 0){echo "greg";}

Check if value exists In MySQL row

I have a php variable: $foo
My MySQL table called data has the following structure:
id var header
1 zj3 http://google.com
I would like to check if $foo is all ready in var row.
If it is I would like to echo header ("http://google.com")
How would you approach this?
Thanks in advance, please ask if any clarification is needed!
Your query should be:
SELECT `header` FROM `data` WHERE `var` = '$foo'
This will return all the headers with a var value of $foo.
$db = mysqli_connect('localhost', 'username', 'password', 'database');
if($query = mysqli_query($db, "SELECT `header` FROM `data` WHERE `var` = '$foo'")){
while($row = mysqli_fetch_assoc($query)){
echo $row['header'];
}
mysqli_free_result($query);
}
first connect to the db
$query = mysql_query("SELECT var, header FROM data WHERE id='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
if($foo == $row['var']){
echo $row['header'];
}
}
EDIT: changed equality statement based on your edit
It's not difficult at all, If I understand correctly then this should help you.
// Query Variable / Contains you database query information
$results = $query;
// Loop through like so if the results are returned as an array
foreach($results as $result)
{
if(!$result['var'])
echo $result['header'];
}
// Loop through like so if the results are returned as an object
foreach($results as $result)
{
if(!$result->var)
echo $result->header;
}
are you asking if $foo matches any of the fields in data, or if $foo=some_field? Here for if you want $foo==var.
$foo='somevalue';
$query="SELECT id, var, header FROM `data` WHERE var='$foo'";
$result=mysqli_query($query);
if($result->num_rows==0)
$loc= 'http://google.com';//default value for when there is no row that matches $foo
}else{
$row=$result->fetch_assoc(); //more than one row is useless since the first header('Location: x') command sends the browser to a new page and away from your script.
$loc=$row['header'];
}
header ("Location: $loc);
exit;
ETA: since you've edited your question, it appears that you want to echo the header column if your search value matches your var column. The above won't work for that.
You just want to know if $var's value is anywhere in that column (any row(s))?
SELECT COUNT(id) FROM data WHERE var = ?;
The result will be the number of rows for which the field var contains the value of $var.
Here's a template for all the "does it exist" questions.
This is the only thing that actually worked for me so far and is not deprecated.
if ($query = mysqli_query($link, "SELECT header FROM data WHERE var = '$foo'")) {
$header = mysqli_fetch_assoc($query);
if ($header) {
// The variable with value $foo exists.
}
else {
// The variable with value $foo doesn't exist.
}
}
else {
// The query didn't execute for some reason. (Dammit Obama!)
}
WARNING!
Even if the variable DOES NOT EXIST the comparison between $query and mysqli_query() will always return TRUE.
The only way --which happened to me-- for the comparison to return FALSE is because of a syntax error in your query.
I don't know why it worked for the guy who wrote the accepted answer, maybe it's an update or maybe he had a syntax error and was so confident that he didn't check if it could ever be TRUE.
Here's the comment someone made for correcting his syntax:
"Add another ) before the { in the first line"
So, the accepted answer is WRONG!

How do I return the numeric value from a database query in PHP?

I am looking to retreive a numerical value from the database
function adminLevel()
{
$q = "SELECT userlevel FROM ".TBL_USERS." WHERE id = '$_SESSION[id]'";
return mysql_query($q, $this->connection);
}
This is the SQL.
I then wrote the following php/html:
<?php
$q = $database->adminLevel();
if ($q > 7)
{
?>
Create a new league
<?
}
?>
The problem I have is that the userlevel returned isn't affecting the if statement. It is always displayed. How do i get it to test the value of userlevel is greater than 7?
Thanks
mysql_query returns a resource. You need to fetch data from that resource by using some of the mysql_fetch_* functions, such as mysql_fetch_row http://php.net/mysql_fetch_row
adminlevel() doesn't return an integer here. It returns a mysql resultset object containing a single row and a single column; the data point contained within happens to be an integer. Presumably, however PHP compares that object to integers happens to alwayus result in its being larger than 7. But it's not comparing the integer you wanted to compare. Try this:
function adminLevel()
{
$q = "SELECT userlevel FROM ".TBL_USERS." WHERE id = '$_SESSION[id]'";
$r = mysql_query($q, $this->connection);
if ( $r and mysql_num_rows($r) ) {
$s = mysql_fetch_assoc($r);
return $s['userlevel'];
} else {
// error handling; your query failed or returned no rows
}
}
mysql_query returns a resource. You then need to fetch the result from this. e.g.
function adminLevel()
{
$q = "SELECT userlevel FROM ".TBL_USERS." WHERE id = '$_SESSION[id]'";
$result = mysql_query($q, $this->connection);
if ($row = mysql_fetch_assoc($result)) {
$level = $row['userlevel'];
} else {
$level = 0; // some default value
}
// free the result resource after using it
mysql_free_result($result);
return $level;
}
If you think about it, in the general case a query can return multiple results so you need a way to retrieve each of these in turn (e.g. a while loop over mysql_fetch_assoc) but in this specific case as you are selecing the userlevel by id you will retrieve either 0 or 1 rows so we can use an if to check for a matching row.
See the documentation for mysql_query for more details.
You are comparing a mysql resource with an integer, so you can expect strange results. Use mysql_result() to fetch one cell from this resource.

Whats the proper way to check if mysql_query() returned any results?

I tried what seemed like the most intuitive approach
$query = "SELECT * FROM members
WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
if ($result)
{ ...
but that didn't work because mysql_query returns a true value even if 0 rows are returned.
I basically want to perform the logic in that condition only if a row is returned.
Use mysql_num_rows:
if (mysql_num_rows($result)) {
//do stuff
}
If you're checking for exactly one row:
if ($Row = mysql_fetch_object($result)) {
// do stuff
}
You can use mysql_fetch_array() instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:
while ($Row = mysql_fetch_object($result)) {
// do stuff
}
This will loop until it runs out of rows, at which point it'll continue on.
mysql_num_rows
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
If none match, then zero will be the return value and effectively FALSE.
$result = mysql_query($query);
if(mysql_num_rows($result))
{ //-- non-empty rows found fitting your SQL query
while($row = mysql_fetch_array($result))
{//-- loop through the rows,
//-- each time resetting an array, $row, with the values
}
}
Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...
To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result = mysql_query($query);
if(mysql_affected_rows())
{ //-- database has been changed
}
//-- if you want to know how many rows were affected:
echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
mysql_query() will only return FALSE if the query failed. It will return TRUE even if you have no rows, but successfully queried the database.
$sql = "SELECT columns FROM table";
$results = mysql_query($sql, $conn);
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
//Hurray
} else {
//Nah
}
This should work.
I used the following:
if ($result != 0 && mysql_num_rows($result)) {
If a query returns nothing it will be a boolean result and it's value will be 0.
So you check if it's a zero or not, and if not, we know there's something in there..
HOWEVER, sometimes it'll return a 1, even when there is nothing in there, so you THEN check if there are any rows and if there is a full row in there, you know for sure that a result has been returned.
What about this way:
$query = "SELECT * FROM members WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
//you could then define your variables like:
$username = $result['username'];
$password = $result['password'];
if ($result)
{ ...
I like it because I get to be very specific with the results returned from the mysql_query.
-Ivan Novak
well...
by definiton mysql_query:
mysql_query() returns a resource on
success, or FALSE on error.
but what you need to understand is if this function returns a value different than FALSE the query has been ran without problems (correct syntax, connect still alive,etc.) but this doesnt mean you query is returning some row.
for example
<?php
$result = mysql_query("SELECT * FROM a WHERE 1 = 0");
print_r($result); // => true
?>
so if you get FALSE you can use
mysql_errorno() and mysql_error() to know what happened..
following with this:
you can use mysql_fetch_array() to get row by row from a query
$result = mysql_query(...);
if(false !== $result)
{
//...
}

mysql count into PHP variable

Let say that we have the following query:
SELECT DISTINCT COUNT(`users_id`) FROM `users_table`;
this query will return the number of the users from a table. I need to pass this value to a PHP variable. I'm using this:
$sql_result = mysql_query($the_query_from_above) or die(mysql_error());
if($sql_result)
{
$nr_of_users = mysql_fetch_array($sql_result);
}
else
{
$nr_of_users = 0;
}
please correct my code where you think is necessary.
Which is the best approach. How do you recommend to do this ?
Like this:
// Changed the query - there's no need for DISTINCT
// and aliased the count as "num"
$data = mysql_query('SELECT COUNT(`users_id`) AS num FROM `users_table`') or die(mysql_error());
// A COUNT query will always return 1 row
// (unless it fails, in which case we die above)
// Use fetch_assoc for a nice associative array - much easier to use
$row = mysql_fetch_assoc($data);
// Get the number of uses from the array
// 'num' is what we aliased the column as above
$numUsers = $row['num'];
Also, an alternative using mysqli, which you should be using anyway for parameter interpolation:
$statement = $connection->prepare($the_query_from_above);
$statement->execute();
$statement->bind_result($nr_of_users);
$statement->fetch();

Categories