i am using this query
$query = "SELECT SQL_CACHE * FROM `like` WHERE `id` ='$id' LIMIT 0 , 1";
$result = #mysql_query ($query); // Run the query.
$row = mysql_fetch_array($result);
$crap= $row['crap'];
is there any faster way to execute this query?
i want to execute this as fast as possible
i am using php
thanks
Do you have an index in place on the id column? That's the only way I can think to speed things up.
And maybe selecting only the crap column specifically instead of *.
If this isn't fast enough for you and you control your server infrastructure, you may want to look into caching solutions like Memcache.
That is as simple as youre going to get. This is not what you should be optimizing. It would be better if you optimize all processes leading to this query and after. This is at its optimum state.
If you just need crap column then select only that column that will increase the speed than selecting all. Similarly select only those columns which you need. IF you need all then the query is in its fine state
It should execute as fast as possible, they don't get simpler than this.
Related
Is it possible to SELECT specific rows and DELETE the selected result in ONE request?
$res = $Connection->query("SELECT * FROM tasks");
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){ ...
The problem is that I have limited Number of queries to my SQL database and I want to minimize it as mush as possible.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it. (So timing doesn't matter much)
For the record, since you are worried about the number of queries, it can be done using mysqli and the mysqli_multi_query-function.
P.S. - I haven't tried this, but since this mysql_multi_query is there in the documentation, it might help... :)
Both SELECT and DELETE need one request individually. And there is no SQL can do this work in the official documents.
On my script, I have about 15 SQL queries just for counting the number of rows and displaying them to the user.
What is the most efficient way?
Should I use:
$stmt=$cxn->prepare("SELECT id FROM items WHERE seller=?");
$stmt->execute(array($username));
echo $stmt->rowCount();
Or this:
$stmt=$cxn->prepare("SELECT count(*) as count FROM items WHERE seller=?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
echo $row['count'];
Thanks in advance.
The short answer is Count(*) will be faster.
However, that assumes your not using the data, if you are going to select the data, and you want a count, then use your first method.
("SELECT id FROM items WHERE seller=?");
If you have an index on the table, then that will return almost instantly.
The rowCount command can be used not only for SELECT queries but also for UPDATE,INSERT etc.
So that's a benefit for that.
However according to the PDO documentation :
not guaranteed for all databases and should not be relied on for portable applications.
So in your case i'd suggest using count without worrying about preformence, though it will slightly faster.
It will be faster to use the MySQL row count. Less bandwidth is needed between PHP and the database.
I want to do something like this:
$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....
Because all I want is the user ID that corresponds to the username.
The usual way would be that:
$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
$the_user_id= $row['userid'];
But is there something more efficient that this?
Thanks a lot, regards
You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)
SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.
As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.
Not only can you, but you should. Unfortunately too many young developers get in the habit of selecting far too much data. Once you run your query, you don't need to do a while loop since you only have one record coming back. Instead, just use the following:
$sql = sprintf( "SELECT userid FROM users WHERE username = '%s'", $username );
$result = mysql_query( $sql ) or die( mysql_error() );
$data = mysql_result( $result, 0 );
if ( $data ) echo $data; // first userid returned
The second parameter of mysql_result() is the row index you would like to retrieve. 0 is first.
The "usual" way is to only select the columns that you need.
Any column that is part of the select and is not needed will slow down the retrieval. Partly because of network traffic and partly because the database engine can apply certain optimizations if only some columns are selected.
And select * is usually frowned upon in production code.
Your query is correct:
$query = mysql_query("SELECT userid FROM users WHERE username='$username'");
This will work if done correctly. Note that $username must be correctly escaped with mysql_real_escape_string. I'd recommend looking at parameterized queries to reduce the risk of introducing an SQL injection invulnerability.
One other thing you can change is to use mysql_result instead of your loop:
$the_user_id = mysql_result($result, 0);
This assumes that know you'll get only one row.
Yes, that's a great optimization practice!
Also, if you want to go a step further and make it super-optimized, try adding a LIMIT, like this: $query=mysql_query("SELECT userid FROM users WHERE username='$username' LIMIT 1");
This, of course, assumes you expect only one userid to be returned and will make the database engine stop once it finds it.
But, the most important thing: ALWAYS ESCAPE/SANITIZE YOUR INPUT DATA! (can't stress this well enough)
You can do this with a single line of code
echo array_values(mysqli_fetch_array($mysqli->query("SELECT name FROM user WHERE id='$userid'")))[0];
You must connect to the database as shown below before using this
$mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE');
Credits to #samuel t thomas
Two quick (I hope!) questions:
Counting rows
Is it more efficient to use COUNT(id) in an SQL query, or to just select all the rows and use PHP's mysql_num_rows() function on the returned resource? Would this depend on the size of the results query? Is there a fairly easy way of determining the answer to this question?
Results arrays
At the moment, I am using COUNT(id) in a query, and then obviously using mysql_query() and mysql_fetch_array(), as follows:
$sql = "SELECT COUNT(id) FROM TABLE1;";
$resource = mysql_query($sql) or die(mysql_error())
$result = mysql_fetch_array($resource);
$count = $result[0];
and this returns the number of rows fine. However, I'm surprised that
$count = mysql_fetch_array($resource)[0];
doesn't work; I get the error:
Parse error: syntax error, unexpected '[' in C:\ServerDocs\file1.php on line 44
is there an easy explanation as to what's going on?
Thanks in advance,
Chris
It depends on the situation, but SELECT COUNT(*) is normally faster.
The reason is simply that using mysql_num_rows(), the database
server has to actually build the result set. With a COUNT(*), on the
other hand, the DB may be able to determine the number of rows just
from indexes, which is much faster. So if all you want is the count,
then mysql_num_rows() ends up doing a lot more work for the same
result.
Another down side is that mysql_num_rows doesn't work with
unbuffered queries. So if you need to work with very large result
sets, using mysql_num_rows might not be an option. However, COUNT(*)
is always available.
$count = mysql_fetch_array($resource)[0];
This type of statements are not possible in current version of php.
So, better use
$no_of_rows = mysql_fetch_array($count);
echo $no_of_rows[0];
1) mysql_query gets all the results and the you do a count on the results. Therefore performance is related to the number of results. If you do count(*) it is a DB select which results only one row/column. In this case database does everything for you, which is usually considered better.
2) $count = mysql_fetch_array($count)[0]; is not possible. Do the following:
$count = mysql_fetch_array($count);
echo $count[0];
I do have 8 tables. when a query fires from search page data from all these 8 tables is pulled out and displayed on the result page. What I want to know is which is the best optimized query method for this process??
what I do now is :
$result = mysql_query("SELECT * FROM TG_dat,TG_dat1,TG_dat2,TG_dat3 WHERE
TG_dat.web = TG_dat1.web AND TG_dat.web = TG_dat2.web AND TG_dat.web =
TG_dat3.web AND TG_dat.web='".$uri."'")or die(mysql_error());
or do i need to use this??
$result = mysql_query("SELECT * FROM TG_dat WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat1 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat2 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat3 WHERE web='$uri'")or die(mysql_error());
Your existing query is perfect - always try to use as few queries as possible.
Less calls to the database is generally better, so you can use the first one.
However, rather than putting all of your tables directly into your FROM clause, it's generally considered good practice to use a join on related tables (which it appears these tables are).
For example:
"SELECT *
FROM TG_dat
LEFT JOIN TG_dat2 USING(web)
LEFT JOIN TG_dat3 USING(web)
WHERE TG_dat.web = '$uri'"
Don't worry so much about the two variations in query you've given - they'll perform more or less the same, but if performance is the issue then the first would be my choice - the single query involves a single round-trip to the server and it's easier to handle the results on the client. It's better to concern yourself with the SELECT *, SELECT <the fields you need> would make more sense - you don't need to have the web field returned multiple times in the results.
your existing query is good. The point is to limit querying db server for better effieciency