Question if my code is a low resources one - php

Hi please 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).

Related

Cannot cast string to int (php)

I am trying to finish my question of the day script. I have a random number generator (external) which is inserted into a table daily. I take that number and pull the corresponding question from another table.
// Query 1
$query1 = "SELECT $field1 FROM $table1 WHERE id=1";
$result1 = mysqli_query($con1, $query1);
// Query 2
$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $result1";
$result2 = mysqli_query($con2, $query2);
// Display question
while($row = mysqli_fetch_array($result2)) {
echo $row['question'];
}
$result1 is pulling a random number, lets say its 9. When $result1 is used to pull the question, it doesn't work but when I replace $result1 with number 9, it works. I experimented with syntax and eventually figured it could be a problem with a string vice an integer.
I tried to cast it as an integer but it keeps assigning the value of $result1 to 1. I am at a loss. I don't understand if the string is a 9, how converting it to an integer would change its value.
I feel like I've tried everything after days of experimenting out there but I am sure it is something very simple. Please help.
You're right, it's something very simple. You need to fetch the row to get the value:
$row = mysqli_fetch_assoc($result1);
$qnum = $row[$field1];
$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $qnum";
You seem to understand this in general, since you call mysql_fetch_array to get the results of the second query. Why should the first query be any different?
However, you can do all this in one query:
$query2 = "SELECT t2.$field2
FROM $table1 t1
JOIN $table2 t2 ON t1.$field1 = t2.QNum
WHERE t1.id = 1";
Have you checked whats returned in $result1 ??
it should be an object which cannot be used inside the second mysql query. First you have to get the value from that query by fetching the query.
$result1 = mysqli_query($con1, $query1);
$row = mysqli_fetch_array($result1, MYSQLI_NUM);
$random_number = $row[0];
this $random_number then can be used in the second query. hope this will fix your error.

How to display field from MySQL?

I'm trying to display a field from my MySQL database. It's in the table tblproducts in the row with the id is set to 1. And under the column qty.
This is the code I'm using:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database_name");
$available = "SELECT qty FROM tblproducts WHERE id = 1";
$result = mysql_query($available);
echo $result;
?>
However, I keep getting this message: Resource id #2
I've done a bit of research and seen where other people are having similar problems but most of them are trying to display their data in an HTML table whereas I just need the data from 'qty' to display. And of course I'm definitely not a MySQL guru.
Can anyone help me out with this please?
Try changing this:
$result = mysql_query($available);
To this:
$result = mysql_result(mysql_query($available), 0);
Let's start from the start. (I'll assume you have the connection set)
Form the query
$query = "SELECT `qty`
FROM `tblproducts`
WHERE `id` = 1";
Execute the query
$run = mysql_query($query);
Now, put the result in an assoc array
$r = mysql_fetch_array($run);
See the contents of the array
echo $r['qty'];
It's also advised that you move up from mysql to either mysqli, or PDO. PDO is preferred as you're not bound to the MySQL database model.
Try this:
Here you need to generate associative array and then get the resulting row.
$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";
$run = mysql_query($query);
$r = mysql_fetch_array($run);
echo $r['qty'];
-
Thanks

Why does this only display one of my records?

I am trying to get pagination working on my website. Everything should be working but this only displays one product, however that should be 8 products. Anybody know what's wrong?
Thanks in advance.
else {
$query = "SELECT COUNT(*) FROM products";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
{
echo '<div style="margin-bottom:10px;display:inline-block;background-color:#E3E3E3;width:190px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row[4]).'"><br><div align="center"><b>'.htmlspecialchars($row[1]).'</b><br><h6>€'.htmlspecialchars($row[3]).'</h6></div></div>';
};
echo ' ';
echo '<br><br><div style="margin-left:330px;">';
echo $pages->display_pages();
echo '</div>';
}
?>
mysql_fetch_row() only fetches one row at a time. You need to call it repeatedly to display all rows, like this:
while ($row = mysql_fetch_row($result)) {
// handle single row
}
I suggest you consider using mysql_fetch_array() instead. Then you will not have to rely on the order of the columns anymore and your code becomes more legible:
$row[0] becomes $row["serial"] etc.
Try reading the articles that #Kush linked. See here for a PHP-specific discussion.
You do not seem to be using mysql_fetch_row() properly
The following code is vulnerable to SQL injection because $page->limit does not appear to be sanitized
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
Stop using mysql_* functions as they're deprecated. Use PHP database objects (PDO) instead because PDO allows parameter binding which protects you from sql injection.
You can read up on using PDO here
because of this line
$row = mysql_fetch_row($result);
should be
while($row = mysql_fetch_row($result)){...
Change the line
$row = mysql_fetch_row($result);
to
while ($row = mysql_fetch_row($result))

most efficient way to print a list of names based off a csv using php and mysql

I have an array of player's IDs. There will generally be about 5 players, not likely to be more then a dozen:
$cplayers= array(1,2,5);
I want to display the players names as a list.
$query = "SELECT username,id FROM users ORDER BY id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$playercounter =0;
while ( $row = mysql_fetch_array($result) ) {
if ($row['id'] == $cplayers[$playercounter]) {
echo "<li>".$row['username']."</li>";
$playercounter++;
}
}
So I'm pretty sure this isn't the most efficient way I could do this. Would it be better to do individual queries?
Also is there a good way to exit the while loop once $cplayers is done?
just change your query to this:
$query = "SELECT username,id FROM users WHERE id IN (".implode(",",$cplayers).")ORDER BY id";
this will return the correct players you're looking for.
Based on how I'm interpreting this, I'd use the MySQL IN clause, e.g.
$id_list= array(1,2,5);
$sql= 'SELECT username FROM users WHERE id IN('. join(",",$id_list) .') ORDER BY id';
$result= mysql_query($sql) OR die(mysql_error());
while($row= mysql_fetch_assoc($result)) {
echo "<li>{$row['username']}</li>";
}
This targets only those id values in the list, is that what you want?
Well apparently the answer is rather to normalize my database, have a separate (third) table for the join of the two rather than using an array w/in the second table.

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories