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.
Related
I execute this query with php and odbc driver
$sql="DECLARE #Auftrag int;
DECLARE #date_now datetime = getdate();
EXEC #Auftrag=EHS.dbo.SP_ANZEIGE
#Tablet=1,
#Status=0,
#KuNr='K015538';
SELECT 'generatedID'=#Auftrag;";
$res = odbc_exec($db1_link, $sql) or die(odbc_errormsg()); // returns resource(13)
$firstRow = odbc_fetch_array($res); // dies error
If i do odbc_fetch_array the error "No tuples available at this result index" is thrown.
If I run the exact same query in Management Studio everything works fine. It shows me the computed generatedID. What is the difference?
greets Alex
Try to prefix the query with:
set nocount on
That prevents SQL Server from sending rowcount updates, which UNIX clients sometimes mistake for actual rowsets
I had this same problem. In my case I was executing like this
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
while ($data = odbc_fetch_array($resultSet)) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);//failed here
while ($data2 = odbc_fetch_array($resultSet2)) {
//something here
}
}
and I changed like this and it worked
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
// Create an array and store the results
$queryResult = array();
while ($data = odbc_fetch_array($resultSet)) {
// push the required content into the array
$queryResult[$data['id']]['name'] = $data[name];
}
foreach($queryResult as $row) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);
while ($data2 = odbc_fetch_array($resultSet2)) {
// something here
}
}
For example, for some queries like SELECT MAX(field), the query result is usually only a field value, rather than returning rows to you.
Now the field of the value I wanna get is integer type.
As I'm a beginner of php, how can I get that value from the query result?
As I do the following
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo $result;
Then nothing is echoed out.
I have check the db connection made by mysqlconnect, and it's got no problem.
And I tried this query in MySQL at phpMyAdmin, then the query is what I want, too?
So why would it be like that, and any solution?
Thanks!
You will always retrieve rows back from an SQL query, even if there's only one row with one field. You can directly retrieve a specific field of a specific row using mysql_result:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo mysql_result($result, 0, 0);
$query = "SELECT MAX(stringid) as val FROM XMLString";
$result = mysql_query($query, $link);
$rows = mysql_num_rows($result);
if($rows > 0) {
$rstAry = mysql_fetch_array($result);
echo $rstAry['val'];
}
Try This
mysql_query is not printing results. Maybe try this:
echo mysql_result($result);
You are not getting any result because mysql_query returns a database object.
You will need to process this "database object" using mysql_fetch_array. This command 'fetches' an array out of a MySQL "database object". The array you are fetching is the rows your query produced. In your case, it is just one row.
Here is the code:
This step sets your query:
$query = "SELECT MAX(stringid) as val FROM XMLString";
This step will run your query, and return the database object:
$result_database_object_whatever = mysql_query($query, $link);
This step will process the database object, and give you an array of the queried rows:
$result_array = mysql_fetch_array($query, $link);
This step will echo the first row returned by your query:
echo $result_array[1];
You can do something like this:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
$fetch = mysql_fetch_assoc($result);
echo $fetch['stringid'];
The mysql_fetch_assoc() function retrieves the data in an associative array.
Would it help to give the max a name you could reference? Also ifyou think there's syntax errors you could just add the error to help clarify.
$query = "SELECT MAX(stringid) as maxNum FROM XMLString";
$result = mysql_query($query, $link) or die(mysql_error());
echo $result;
The below script is called every 5 seconds. The issue is that if the server is responding slow, one entry in "blog" can get selected twice in a row because the server hasn't had time to set "done" to "1" yet. Is there an industry standard (or whatever you call it) way to prevent this from happening?
$result = mysql_query("SELECT * FROM blogs WHERE done=0 LIMIT 1");
$rows = mysql_num_rows($result); //If there are no entries in with done set to 0, that means we've done them all; reset all entries to 0.
if($rows == 0)
{
mysql_query("UPDATE blogs SET done=0 WHERE done=1");
}
else
{
while($row = mysql_fetch_array($result))
{
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id]");
// Do stuff
}
}
I think I could change it to
while($row = mysql_fetch_array($result))
{
if($row['done'] == 1){ die; }
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id]");
//Do stuff
}
But will that really fix the problem? I would imagine there would be a better way that really prevents it from happening without a shadow of a doubt.
I think the best way to prevent selecting the same row is using SELECT GET_LOCK("lock_name"); and SELECT RELEASE_LOCK("lock_name");. When you get a lock from mysql server, other processing trying to get a lock will wait for the lock to be released. Below is a sample implementation:
<?php
function getLock($lockName, $dbc) {
$query = "SELECT GET_LOCK('".$lockName."', 0)";
$result = mysql_query($query, $dbc);
$lockResult = mysql_fetch_row($result);
$lockResult = $lockResult[0];
return $lockResult == 1 ? true : false;
}
function releaseLock($lockName, $dbc) {
$query = "SELECT RELEASE_LOCK('".$lockName."')";
$result = mysql_query($query, $dbc);
}
// CONNECT TO DATABASE
$dbc = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $dbc);
$loopQueue = true;
$rowsProcessed = 0;
// MAIN QUEUE LOOP
while ($loopQueue) {
// TRY UNTIL GETTING A LOCK
$queueLockName = 'queue_lock_1';
while (getLock($queueLockName, $dbc) === true) {
// WE GOT THE LOCK, GET A QUEUE ROW WITH PENDING STATUS
$query = 'SELECT * FROM test WHERE status = 0 ORDER BY ID ASC LIMIT 1';
$result = mysql_query($query, $dbc);
if (mysql_num_rows($result) < 1) {
// SINCE WE DON"T HAVE ANY QUEUE ROWS, RELEASE THE LOCK
releaseLock($queueLockName, $dbc);
// WE DONT NEED TO LOOP THE MAIN QUEUE ANYMORE SINCE WE DONT HAVE ANY QUEUE ROWS PENDING
$loopQueue = false;
// BREAK THIS LOOP
break;
}
// WE GOT THE QUEUE ROW, CONVERT IT TO ARRAY
$queueRowArray = mysql_fetch_assoc($result);
// UPDATE QUEUE ROW STATUS TO SENDING
$query = 'UPDATE test SET status = 1 WHERE id = '.$queueRowArray['id'];
mysql_query($query);
// RELEASE THE LOCK SO OTHER JOBS CAN GET QUEUE ROWS
releaseLock($queueLockName, $dbc);
// DO STUFF ...
// UPDATE QUEUE ROW STATUS TO PROCESSED
$query = 'UPDATE test SET status = 2 WHERE id = '.$queueRowArray['id'];
mysql_query($query);
$rowsProcessed++;
}
}
echo "\n\n".'process finished ('.$rowsProcessed.')'."\n\n";
I would have given a go to transactions. Here is an example in another StackOverflow question
Just a question: What happens if the server is even slower? For instance, the select statament takes so long (e.g. 5 seconds) that once it finishes (returning 0 rows), the new select is executed (returning 1 or more rows)
MySQL documentation
$result = mysql_query("SELECT * FROM blogs WHERE done=0 LIMIT 1");
$rows = mysql_num_rows($result); //If there are no entries in with done set to 0, that means we've done them all; reset all entries to 0.
if($rows == 0)
{
mysql_query("UPDATE blogs SET done=0 WHERE done=1");
}
else
{
while($row = mysql_fetch_array($result))
{
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id] AND done=0");
if(mysql_affected_rows() != 1)
die();
// Do stuff
}
}
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]);
?>
I have the following code and it should return just one value (id) from mysql table. The following code doesnt work. How can I output it without creating arrays and all this stuff, just a simple output of one value.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = map_query($query);
echo $result;
I do something like this:
<?php
$data = mysql_fetch_object($result);
echo $data->foo();
?>
You have to do some form of object creation. There's no real way around that.
You can try:
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
//$result = map_query($query);
//echo $result;
$result = mysql_query($query); // run the query and get the result object.
if (!$result) { // check for errors.
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result); // get the single row.
echo $row['id']; // display the value.
all you have is a resource, you would still have to make it construct a result array if you want the output.
Check out ADO if you want to write less.
Not sure I exactly understood, what you want, but you could just do
$result = mysql_query('SELECT id FROM table WHERE area = "foo" LIMIT 1');
list($data) = mysql_fetch_assoc($result);
if you wish to execute only one row you can do like this.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo $row[0];
there have been many ways as answered above and this is just my simple example. it will echo the first row that have been executed, you can also use another option like limit clause to do the same result as answered by others above.