i use this query for fetching data from database
how can i optimize and use best code for this connection?
connect();
$games_sql = mysql_query("SELECT gameid,mizbanid,mihmanid,score1,score2,gamedavar,gamestadium,now FROM games WHERE gameweek='$site_week' ORDER BY now ASC LIMIT 9");
for( $i = 0; $i < mysql_num_rows( $games_sql ); $i++ ) {
$gameid = @mysql_result( $games_sql, $i, 0);
$mizbanid = @mysql_result( $games_sql, $i, 1 );
$mihmanid = @mysql_result( $games_sql, $i, 2);
$score1 = @mysql_result( $games_sql, $i, 3);
$score2 = @mysql_result( $games_sql, $i, 4);
$gamedavar = @mysql_result( $games_sql, $i, 5);
$gamestadium = @mysql_result( $games_sql, $i, 6);
$now = @mysql_result( $games_sql, $i, 7);
$gametimeanddate = jdate("l d M y ساعت G:i", $now);
$gamedate = jdate("l d M y", $now);
$gametime = jdate("G:i", $now);
`connect()` function include `mysql_connect` & `mysql_select_db`
how can i optimize this code for low user_connection
to database and high speed ?
Why don't you query the database once to catch all information? Take a look at this:
connect();
$sql = 'SELECT
gameid,
mizbanid,
mihmanid,
score1,
score2,
gamedavar,
gamestadium,
now
FROM games
WHERE gameweek = ' . $site_week . '
ORDER BY now ASC
LIMIT 9';
$query = mysql_query($sql);
if(mysql_num_rows($query)) {
while($Result = mysql_fetch_object($query)) { //loop trough results
print_r($Result); //prints the results.
echo $Result->gameid; //this is how you echo the data
}
}
Be aware that the mysql_query function is deprecated and needs to be replaced by mysqli :) .
You could always use cache and memcache as an optimizing solution. You can cache your queries and for the rest requests you can pop if from cache
Well There is always a mile to go.. You can do optimization in several ways, with php code as well as with your Query, however you shouldn't use things that are about to extinct
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_stmt_num_rows()
PDOStatement::rowCount()
If you just want to count the rows you should better use:-
SELECT COUNT(*) FROM SomeTable
And you should not use single quotes That has benefit over double Quotes
and As mentioned by NullPointer, you should not use @ to suppress error message. Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.