Question if my code is a low resources one
Hi plea开发者_StackOverflow社区se tell me if this is a low resources piece of code, and if it is not how shall I change it ? Thank you!
$query = 'SELECT MAX(ID) as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$postid = $row['maxidpost']+1;
echo "p=$postid";
The improvement is debatable, but:
$query = 'SELECT MAX(ID) +1 as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "p = ". $row["maxidpost"];
You can do math in SQL statements, saving you from having to do the operation in PHP.
It'd be nice to know what you're using this for - if it's the next id to be inserted, using AUTO_INCREMENT would be safer. SELECT statements are generally given higher priority over INSERT/UPDATE/DELETE, and thus can read before an insert from another source -- which would risk duplicates.
Because you are returning one row, you should do something like:
$query = 'SELECT MAX(ID) as maxidpost FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$postid = $row['maxidpost']+1;
echo "p=$postid";
Otherwise seems about as good as you could do.
You can recalculate the post code after each post. Start with zero. Select it from the database, use that id, add one, save back to database.
Or you could use auto increment (if that is possible).
精彩评论