$result equals nothing if mysql column not found? - php

How could i get $result too equal nothing if the column doesn't exist in PHP?
I was thinking something like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1")or die ($result = '');
But i was told thats wrong.

It's wrong because you're killing the script with die when a DB error occurs, rather than doing stuff when you find no row.
What you presumably need is more like:
$result = mysql_query($query);
if ($result) {
if ($row = mysql_fetch_assoc($result)) {
// do stuff with row
} else {
// do stuff without row
}
} else { // not needed but left here for illustration purposes
// this is the part that would occur, had you called mysql_query(...) or die;
die(mysql_error());
}

$result=mysql_query("SELECT * FROM users WHERE username= '$key' LIMIT 1")or die (mysql_error());
then check the result of mysql_num_rows()

If you mean that the result returns 0 rows, you can check with mysql_num_rows, like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0)
$result = '';

Your code will set $result to '' if there's an error, in which case mysql_query returns false. It will also halt the code, since you're calling die(). An empty result set is not an error, however. In that case mysql_query returns a valid resource identifier with no rows. If I understand your question, this is what you want to do:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0){
$result = '';
}

<?php
// Here I assume you're using PHP PDO
$pdo = new PDO("mysql:server=localhost;dbname=mydatabase", "root", "");
$result = $pdo->query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
$errorcode = $pdo->errorCode();
$errorinfo = $pdo->errorInfo();
// Columns doesn't exist
if($errorcode == "43072") $result = "";
// Other error...
else if($errorcode != "00000") die("MySQL Error: " . $errorinfo[2]);
?>

Related

PHP If variable equals

I am trying to show some text depending upon what a status is set to in a db table.
See my code below:
$result=mysql_query("SELECT * FROM hr_recruitment_stages where vacancy_ref='$vacancyref' order by added_on DESC limit 0,1")or die('ERROR 315' );
$row = mysql_fetch_array($result);
$stage_name = $row ['stage_name'];
if($stage_name['stage_name'] == 'Shortlisting') { echo"Shortlisting"; } else { echo"Not Shortlisting"; } ?>
However this doesnt seem to be working properly as it is showing as Not Shortlisting even when stage_name equals Shortlisting.
Any ideas why?
Its variable type mistake. Check your assigned variable, you assigned the Array Element not the entire array. so try like below.
<?php
$result = mysql_query("SELECT * FROM hr_recruitment_stages where vacancy_ref='$vacancyref' order by added_on DESC limit 0,1") or die('ERROR 315' );
$row = mysql_fetch_array($result);
$stage_name = $row['stage_name'];
if($stage_name == 'Shortlisting') {
echo"Shortlisting";
} else {
echo"Not Shortlisting";
}
?>
Refer this Article for PHP Array understanding.
http://php.net/manual/en/language.types.array.php

how to get the number of rows of mysql db with php

i would like to get the number of rows of a mysql database table with one single statement or a function
include "opendatabase.php"; //opens database
while (NUMBEROFROWS > 0){
//do something
}
the NUMBEROFROWS should be replaced with the statement that returns the number of rows
i already tried to create a function
function getRowNumber(){
$query = "SELECT COUNT(*) FROM `votes`";
$result = mysql_query($query, $connect);
list($length) = mysql_fetch_row($result);
return $length;
}
but it does not work if i dont put the include "opendatabase.php"; in it.
what am i doing wrong
$result = mysql_query("SELECT * FROM tablename");
if (mysql_num_rows($result) > 0) {
// rows found..
}
the problem is that include "opendatabase.php"; runs in another scope like described here
http://www.php.net/manual/en/language.variables.scope.php
there is a global $connect missing within the function
Here you go:
function num(){
$data = mysql_query("SELECT * FROM table");
if(mysql_num_rows($data) > 0){
while($row = mysql_fetch_assoc($data)){
// do something with your data..
}
}
}
would this work for you ?
function getRowNumber()
{
$query = "SELECT COUNT(*) as counts FROM `votes`";
$result = mysql_query($query, $connect);
$row = mysql_fetch_array($result);
$counts = $row['counts'];
return $counts;
}

MYSQLI_NUM_ROWS ALWAYS RETURNING 0

i'm trying to get rid of a bug ASAP. I'm using mysql_num_rows but it ALWAYS returns 0. And i dont know if it's because i have the wrong syntax or what... can you guys help me? here's the code;
<?php
include_once("checklogin.php");
$u = "";
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: http://www.myswesite.com/login.php");
exit();
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($connection, $sql);
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "User does not exist or is not yet activated, press back";
exit();
}
?>
You have to use store_result to buffer the result set before you can get the num rows.
$user_query = mysqli_query($connection, $sql);
mysqli_store_result($connection);
$numrows = mysqli_num_rows($user_query);
See http://www.php.net/manual/en/mysqli-result.num-rows.php:
For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.
i think there is a syntax error in your query when you are passing username try this i think it works for you.
$username=$_SESSION['username'];
SELECT * FROM tbl_users WHERE Username='".$username."'

memcached multiple mysql results

I'm trying to set up memcached to store the results of the query that pulls all the data to be shown on my front page. when i use memcached for one result it works fine, but when I set the query to 'LIMIT 10' and pull the cache it still only shows one result when I var_dump.
Is there something that I am missing? Or am I really only able to store one row at a time?
My basic syntax is as follows (result is assuming key has been set):
$sql = "select * from active limit 10";
//create an index key for memcache
$key = md5('query'.$sql);
$result = $memcache->get($key);
var_dump($result);
edit: added entire code i am trying to work with
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
$sql = "select * from active limit 10";
$key = md5('query'.$sql);
$result = $memcache->get($key);
if($result == null) {
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
if(mysql_num_rows($qry)> 0) {
$result = mysql_fetch_object($qry);
echo "THIS IS NOT CACHE<br>";
var_dump($result);
//store it
$memcache->set($key,$result,0,10);
}
}
else {
echo "this is cached<br>";
var_dump($result);
}
You are using:
$result = mysql_fetch_object($qry);
which only retrieve a single record from the database.
What you need to do is loop through and build an array of objects:
while ($result[] = mysql_fetch_object($qry));
which you can then serialize and cache.
Your code should then look something like this:
...
if($result == null) {
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
while ($result[] = mysql_fetch_object($qry));
// cache it
$memcache->set($key,serialize($result),0,10);
}
...
You need to loop through your results, I'd recommend this:
$cachedResults = $memcache->get($key);
if (!empty($cachedResults)) {
var_dump(unserialize($cachedResults));
exit;
}
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
while ($row = mysql_fetch_object($qry)) {
$results[] = $row;
}
$memcache->set($key, serialize($results));
Remember, if you already have the key in cache, then it will never hit the query to reload the correct result set, so flush it first, then try this code snippet.

Quering integer in MySQL over PHP

I'm working with a table ("Item") which has the field "Aprovado" and it's an integer that checks if the item is approved or not (1 for yes, 0 for no) (not my table, I would have chosen proper boolean).
I know there are items there, and I know there are lots of items with "Aprovado" set to 1. (I am successful with queries "SELECT * FROM Item ORDER BY ItemID ASC")
yet, when I do:
mysql_select_db($theDatabase, $db) or die("Could not find database.");
$query = "SELECT * FROM Item WHERE Aprovado = 1";
$resultID = mysql_query($query, $db) or die("Data not found.");
It just returns "Data not Found." What's wrong?
Could try changing your die(...) into:
die('Invalid query: ' . mysql_error());
That will show you the actual MySQL error.
mysql_query does not return FALSE if the query returns no data. It only returns false on an error condition:
$result = mysql_query($query, $db) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
die("Data not found");
}
$row = mysql_fetch_assoc($result);
$resultID = $row['resultID'];

Categories