PHP SQL query results - php

Alright, I'm pretty confident I did this only a few days ago, although I may be going crazy. I am attempting to loop through an SQL result array for example..
$query = mysql_query("SELECT * FROM `my_table`");
$result = mysql_fetch_assoc($query);
Now $result should return multiple rows.. and it does if I loop through it using a while loop. Unfortunately, Im trying to access this data with a foreach loop, and for some reason it will not work. Its only giving me the first row and print_r($result) only gives me the first row as well.
foreach($result as $name => $value)
echo "$name = $value\n";
Any suggestions would be appreciated!
** EDIT:
I love all of the smart answers.. I know the website for the php manual and I know what mysql_fetch_assoc() returns. Here is my solution:
function returnSQLArray() {
$returnArray = array();
$row = 0;
$query = mysql_query("some sql");
while($result = mysql_fetch_assoc($query)) {
$returnArray[$row] = $result;
$row++;
}
return $returnArray;
}

$result = mysql_fetch_assoc($query); returns a single row... you need to loop fetching each row. You're looping through that one row to extract each column.

What Vladson is sarcastically pointing out is nonetheless very true. My forays into PHP programming (many years' worth) have been ever-sprinkled with a great many readups on the php.net site. I'd call it the best online programming documentation in existence, far beating any other language I've used in 20 years.. mostly because of the amazing calibre of the community contributions.
Also, I'd highly recommend abstracting what you're talking about into a db helper class. Reference perhaps the PHPBB code for an example. PHPBB code may be less OO than is ideal, but it's still a good reference point for architecture. And, don't just do this because you may switch out your data layer or change the version, but because it makes it trivial to introduce common error reporting, query logging, data caching, and many other such useful features. This also makes it easier to juggle more than one connection.
Example might be so that you can expose an interface more like: (excuse the very ADODB nature here, but it's still a nice way to think of MySQL, too)
include "db.inc.php";
$SQL = "SELECT * FROM user WHERE id=123";
$oDB = new Database("localhost", "database", "user", "password");
$oRS = $oDB->NewRecordSet($SQL);
while( $data = $oRS->Read() ) {
// do stuff
}
In this manner, the pages have to worry less about the tedium of accessing the data, and can just think more about how to filter the data and what to do with it.

while ($result = mysql_fetch_assoc($query))
{
// do stuff
}

There is a thing called Manual http://www.php.net/manual/en/function.mysql-fetch-assoc.php examples are also there (a lot of them)

Related

PHP/mysql: Is changing (SELECT, {resource}) to ({resource}, SELECT) a viable temporary patch for mysql_* to mysqli_*?

On first inspection of the differences in application of the mysql*() and mysqli*() families of functions, it appears to me that
$seta = mysql_query("SELECT * FROM table WHERE field = $Filter", $database);
Can be rapidly replaced with:
$seta = mysqli_query($database, "SELECT * FROM table WHERE field = $Filter");
Similarly, it also appears that
IF ($A = mysql_fetch_array($seta)) {
do {
//code here
} while ($A = mysql_fetch_array($seta));
}
Could be replaced with:
IF ($A = mysqli_fetch_array($seta)) {
do {
//code here
} while ($A = mysqli_fetch_array($seta));
}
Will this work the way I am expecting it to? As it worked before mysqli*()?
PLEASE NOTE: I am not asking if I SHOULD do this, only if I CAN do this. I know full well that slapping a band-aid on a broken leg is useless... That said, I don't have that many hours of coding/testing time before the Demo in March this is being prepped for.
Yes, I understand the this is vulnerable code. I won't go to production without safeguards. I also realize that I am not using all the power of the mysqli*() family of functions this way.
My goal is to refactor everything properly when there isn't such a heavy time crunch (Yes, I know, famous last programmer words). I just need the patched code to run for a Demo then I can retire it.
I have high hopes that with a working prototype -- both in situ and on a server I'm spinning up just to demonstrate the need for software updates -- I'll be able to leave the PHP v4.x blues behind.
Project:
PHP/MySQL better user searching
Also checked:
How to upgrade from mysql* to mysqli*?
PHP Migrating from mysql* to mysqli
Above titles were trimed of underscores to prevent formatting
The quick and dirty method, with emphasis on dirty, is to do it this way by converting mysql_query to mysqli_query and so on. The problem is mysql_query is really clunky to use so preserving that coding style is not going to help clean anything up.
Although I'd strongly recommend switching to PDO, it's a more flexible and capable database layer, if you want mysqli then what you want to do is employ parameterized queries and bind_param to add user data to your query. This solves the vast majority of SQL injection bugs out of the gate. I'd also suggest using the object-oriented interface so your updated code is obvious. The difference of a single i can be easy to overlook, plus it's typically less verbose.
In other words, your replaced code looks like:
$stmt = $database->prepare("SELECT * FROM table WHERE field=?");
$stmt->bind_param('s', $filter);
$res = $stmt->execute();
If you're disciplined about doing this you should catch all your SQL mistakes.
PDO is nicer because of named parameters:
$stmt = $database->prepare("SELECT * FROM table WHERE field=:filter");
$res = $stmt->execute(array('filter' => $filter));
That usually means less code in the long-run.

MySQL query to PDO

I've been suggested to migrate from the deprecated MySQL to MySQLi or PDO, I finally got around to it as it'll help my project without wasting too much time. I've been reading a lot on some great articles and websites, but I'd like the best suggestion on how to fetch array with PDO, I can do it with a while loop but I dislike it, how would I convert this current code to PDO.
public function User_Details($_iD){
$_iD = mysql_real_escape_string($_iD);
$query="SELECT _iD,_iPassword,_iEmail,_iNickname,_iUsername,_iProfilePicture,_iFriendCount FROM users WHERE _iD='$_iD' AND _iStatus='1'";
$result = mysql_query($query) or die(mysql_error());
$data = mysql_fetch_array($result) or die(mysql_error());
return $data;
}
I am able with a while loop but as I said, that's not what I'm interested in unless it's a better option.
PDO :
$sql = "SELECT _iD,_iPassword,_iEmail,_iNickname,_iUsername,_iProfilePicture,_iFriendCount FROM users WHERE _iStatus='1'";
foreach ($db->query($sql) as $row){
print $row['_iD'] .' - '. $row['_iUsername'] . '<br />';
}
It would also be wise to actually study how PDO is different from old methods instead of trying it the old way with new tools. One of the things that PDO offers is to create prepared statements, which you can execute, and fetch in various ways. I think the fetchAll method is exactly what you are looking for.

Need to return/echo PHP PDO results from database

Well I've did do my research and I just can't seem to figure this out. So long story short, I'm using something like this:
btw, "(WebsiteInfo)" is just to sensor out my website/database information.
$SQL = new PDO('mysql:dbname=(WebsiteInfo);host=(WebsiteInfo);charset=utf8', '(WebsiteInfo)', '(WebsiteInfo)');
$SQL -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$SQL -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Now, that's just currently just to start the database connect up. Which btw is mostly just a copy/paste code I found on this website too which is to prevent MySQL injection. Actually from this link How can I prevent SQL injection in PHP?. If there's anything wrong with it, I wouldn't mind advice or tips. As long as if it makes sense because I just started using databases probably not even a week ago so everything is new to me. Now there's this:
$Exicu = $SQL -> prepare("SELECT `tags` FROM `users` WHERE `user_id` = :a ") -> execute(array( ':a' => 16));
$Exicu is just there, because I have been trying to get the results from the query (if I said that right). Also the 16 is the users ID, but this will change often so that's why 16 isn't just tossed in the prepare statement. I've tried a lot of things but none of them worked. It either didn't work or made the PHP crash.
But anyway, things I already tried for $Exicu is $Exicu->rowCount(), $Exicu->bindParam, a while loop with $row = $Exicu->fetch(), $SQL->query($Exicu)->fetchAll();, a foreach loop with ($Exicu->fetch(PDO::FETCH_ASSOC) as $row), $Exicu->get_result(), echo PDO::query($Exicu);, echo mysql_result($Exicu), and just echo $Exicu. Yes I know, that looks pretty sloppy.
But none of these seemed to work to just show me the tags from the database of the specific user. So that's pretty much what I need help with. There's no problem when I use something like this echo mysql_result( mysql_query("SELECT (etc,etc)") ) but that doesn't have protection from MySQL injections.
I do my PDO queries like this:
$user_id = 16;
$query = $SQL->prepare('SELECT tags FROM users WHERE user_id = :uid');
$query->bindValue(':uid', $user_id, PDO::PARAM_INT);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo $row['tags'];
}
This will select data from the database, bind values in it safely and then we echo out the results.
The loop is needed to iterate through every result returned from the query. You can skip the looping part and create a variable like in the while statement, and use $row as an array with your results.
There is a thing called user defined function.
I am wondering why noone on this site ever using them.
For some reason everyone is ready to make a mile long single line of chained methods, instead of clean and concise function call:
$user_id = 16;
$tags = getone('SELECT tags FROM users WHERE user_id = ?',array($user_id));
there are many ways to create such a function. A quick and dirty one
function getone($sql, $data) {
global $SQL;
$stmt = $SQL->prepare($sql);
$stmt->execute($data);
return reset($stmt->fetch());
}
but of course it would be better to make set of functions and put them in a class

Sorting information from query using while?

I'm trying to get it so that the information retrieved from this query is sorted before be shown onto the page by the messageid, which I have assigned as the primary key. I keep getting this error though:
Warning: krsort() expects parameter 1 to be array, resource given in ...
Here's my code:
<?php
$id = $_SESSION[id];
$messages = #mysql_query("SELECT * FROM messages WHERE receiver='$id'");
$messagecount = mysql_num_rows($messages);
krsort($messages);
if ($messagecount == 0)
{
echo "<br>You have no messages.";
}
else
{
while ($messages2 = mysql_fetch_array($messages))
{
echo "<table width=800 class=\"normaltable\" cellpadding=\"3\" border=\"0\"><tr>
<td class=\"tdmessagesubject\"><b>Subject:</b> " . $messages2['subject'] . "</td>
<td class=\"tdmessagefrom\"><b>From:</b> " . $messages2['sendercallname'] . "</td> </tr>
</table>";
}
}
?>
I thought that $messages was an array but it doesn't seem to be working.
Have a look at the manual page, mysql_query returns a resource, not and array.
And while you're there, read that big red fat warning, the one that says that the mysql_ family of functions is deprecated which among other things mean you should not use them in new code.
I'd also suggest to forget about the more modern mysqli_ successor and skip right away to PDO - it's a modern, well designed API, usable with several database engines and last but not least, it makes working with prepared statements a breeze, and prepared statements are probably the least expensive yet most effective defense against sql injection.
But back to the order of the day: when you want a database resultset to be ordered in some way by far the easiest way is to let the database server sort it, like this:
$messages = #mysql_query("SELECT * FROM messages WHERE receiver='$id' order by messageid");
There are a couple of good reasons why you should let the db sort the data and not try to do it yourself:
that way you're forced to load up the entire resultset in memory, which is inefficient and with big resultsets it can exhaust the memory available to php
if your db is well designed, chances are that the data are already indexed on the column you want to sort on, which means that the server doesn't actually have to sort the data when returning them, making the whole operation a lot faster.
your $messages variable is not an array. to build array of messages from database query you should use:
$result = #mysql_query("SELECT * FROM messages WHERE receiver='$id'");
$messages = array();
while ($message = mysql_fetch_assoc($result)) {
$messages[] = $message;
}
Here you can find an example use of mysql_fetch_assoc: http://php.net/manual/en/function.mysql-fetch-array.php
If you want to order your messages in database query you should use ORDER BY statement. For example:
$result = #mysql_query("SELECT * FROM messages WHERE receiver='$id' ORDER BY id");
Oh man don't use # to suppress errors unless you have a really good reason.
mysql_query returns a resource: the query result. If you want to sort it you need to either pull out every row into an array first or (better solution) use ORDER BY in the query to get your results in sorted order.
I'd like to say first that Mysql is deprecated in PHP, it is recommended to use the new Mysql extension, Mysqli
Then, you have to extract the results from the resource:
$data = array();
while($row = mysql_fetch_row($messages)) $data[] = $row;

PHP MySQL update a row that has been selected

This is something I used to do in Java, I was wondering if there is an equivelant in PHP.
In Java, I'd do something like this (pseudo only as I've gotten rusty in the last year or so):
preparedStatement = new StringBuilder("SELECT something FROM somewhere");
ResultSet rs = preparedStatement.executeQuery();
while(rs.next())
{
if (someTest)
{
rs.updateRow[1]="someNewValue";
}
}
This is wide of the mark syntactically (and I bet it won't compile) but I hope it explains the kind of thing I was able to do. Not sure if it saved an actual DB query from being run but it did make my code alot cleaner.
So in PHP, I have something like this:
$query = "SELECT something FROM somewhere";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result))
{
if (someTest)
{
//how can I update this row without coding another query?
}
}
Is there an equivelant to this in PHP?
I'm using the vanilla mysql db methods, not mysqli or that other one (pod or something?) but I think I'd be safe to use mysqli on our servers if I need to.
Any help appreciated
Nope, you could however use mysql_fetch_object with a custom classname, and define a save() method on it that will run the update query for you. Keeps the logic out of the loop and in a Model for that data. Or use an full-blown ORM library which does this kind of thing.
As far as I'm aware, you can't update the row without running another query such as:
UPDATE table SET column1="value" WHERE (column2="value");

Categories