MySQL query to PDO - php

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.

Related

How to check SQL(mysql ) result. PHP

In my php.Mysql ($sql) result should be 1.Sysum should not be empty in another word, mysql_num_rows($sel) > 0 should be true.
But actually,mycode can not work.I don't know why.Who can help me?
$conn = new PDO('mysql:host=localhost;port=3306;dbname=hpc' , 'root' , 'Yd');
$Name=$_COOKIE['PName'];
$sql = "select sysnum from hpc where handler='".$Name."' and stat='N';";
$sel=$conn->query($sql);
if(mysql_num_rows($sel) > 0)
{
mycode;
}
Oh boy that went quite fast with your comment, even before mine :P
So, the answer is simple: You can't use mysql_num_rows on a PDO connection. That are two different drivers. Thats like you try to start the car of your wife with your own keys. Principally, both are keys, but they don't work with any car.
Its the same here in your case. mysql_num_rows comes from the OUTDATED mysql driver. (Don't use mysql_* at all, its not longer supported in PHP7 and deprecated). To do it with PDO is the right way, but you have to adapt your code a bit.
$Name=$_COOKIE['PName'];
$sql = "select count(sysnum) from hpc where handler='".$Name."' and stat='N';";
$sel=$conn->query($sql);
$rows = $sel->rowCount();
echo $rows;
Hope that work, if not, let me know. I know I had some troubles the last time I tried to do a rowCount with PDO.
IMPORTANT - DANGER:
Also I really recommend you to take a look at http://bobby-tables.com and learn something about SQL injection. Your code actually is not save at all and your database can be hacked quite easy. Since you're using PDO, nothing stops you from using prepared statements, what would make your code much better.
Hope I could help you. If you have any other questions or something shouldn't work, please let me know.
fetch result into an array and count items using count function, like this:
$Name=$_COOKIE['PName'];
$sql = "select sysnum from hpc where handler='".$Name."' and stat='N';";
$sel = $conn->query($sql)->fetchall();
if(count($sel) > 0){
mycode;
}

Get values from query and return as array

How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

how to use foreach loop in generating the result of mysql_query

Im always using while loop in generating all record in my database, and some of my friend told me that it is better to use foreach in generating record from a database, but i dont know how.
<?php
$query = mysql_query("select * from sampleTABLE");
while($i = mysql_fetch_array){
echo $i['samplefieldName'];
}
?>
My question is, how to display records from my database using foreach? and can some one compare it in the while loop in terms in syntax and generating its result, thank you.
There is no need to use foreach instead of while here as #Zerkms says
while($i = mysql_fetch_array( $query)){
however ou can do this by below code but i am sure its not good approach
$result_list = array();
while($row = mysql_fetch_array($query)) {
result_list[] = $row;
}
foreach($result_list as $item) {
//you can now echo $item ; or whatever you want
}
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Firstly, the mysql_xxx() functions are deprecated. They are not recommended for use. There are two alternatives in PHP that are recommended instead -- mysqli() and PDO.
The older mysql_xxx() functions do not allow you to use foreach to loop through a recordset.
However, both the newer alternative APIs do allow this, as they implement the Iterator interface.
So yes, it is possible to use foreach to loop through a recordset in PHP, but not with the old mysql_xxx() functions.
You could write code like this:
$conn = new mysqli(....);
foreach ( $conn->query('SELECT ....') as $row ) {
print_r($row);
}
or like this:
$db = new PDO('mysql:....', $user, $pass);
foreach ($db->query('SELECT ....') as $row) {
print_r($row);
}
Having said that, please note that it's only been possible to do this with mysqli since PHP v5.4, so you'll need to be up-to-date with your PHP version for that. PDO on the other hand has supported this feature for ages.
They can, of course, both also use a while loop as well, and this is where your friend isn't quite right, because really there isn't any difference between while and foreach here. Switching from while to foreach won't make any difference to the performance of your code. They do the same thing under the hood. foreach in this case is really just "syntactic sugar".
I would strongly recommend switching to one of these newer APIs, even if you don't plan to use foreach to do your looping, because as I say, the old mysql functions are deprecated, which means that they are likely to be removed entirely from future PHP versions. So if you want your code to keep running into the future, you should switch now.
It's not possible to iterate over a result set using foreach.
foreach only works for cases when you already have the data fetched.
So your friend was just wrong and his advice doesn't make any sense.
#zerkms
I also thought like that.. But following works...
My 'tbl_login' table structure also attached as a
<?php
include '../common/dbConnection.php';
class foreachtest{
function foreachtesting(){
$sql="SELECT * FROM tbl_login";
$query_result=$GLOBALS['con']->query($sql);
return $query_result;
}
}
$myobject = new foreachtest();
$result=$myobject->foreachtesting();
foreach ($result as $a){
echo $a['username'];
}
?>
tbl_login MYSQL table screenshot

What is a PHP function to return multiple rows from a mysql query?

I'm relatively new to php, and to this point I've been fine using the mysql_fetch_array function to echo values selected from the database. But now I want to be able to echo the results selected from multiple rows with the same username.
I was just wondering what the most efficient way of doing this was. I could manage to do it using a for loop and counting through each individual query, but I know there must be a more efficient way just using sql, or using a better oho function.
Thank you for the help.
Alex
while($row = mysql_fetch_array($result)) {
// process each row
}
I guess that's all you neeed - have a play and you should get your desired effect! It's best to do it in PHP..
Also you shouldn't use mysql_fetch_array anymore as it's deprecated. Use PDO or mysqli insted. More information you can find here
while($row = mysql_fetch_assoc($result)) {
} or
while($row = mysql_fetch_array($result)) {
}
and mysql_ functions are depreciated now onwards in mysql
SQL is used to query the database your using. PHP is used to format the output from the query. See the manual from PHP.net for more info php.net/manual/en/function.mysql-fetch-array.php . There is no way as far as I know to format the output in rows using SQL.
B.T.W. if this is new code I would advice you to use mysqli instead of mysql.

PHP SQL query results

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)

Categories