Want to convert a function from Mysql to PDO - mysql

function get_country($code){
$query = mysql_query("SELECT country FROM `list_countries` WHERE `code`='".$code."' LIMIT 1");
$country = mysql_fetch_array($query);
return $country['country'];
}
Very new to PDO and have absolutely no idea how to turn this from a mysql function to a PDO one. Any help would be appreciated :)

You need to take PDO database connection handler with you :) From your code I would suggest setting it as global, or you can add additional parameter to all the functions.
$dbconn = new PDO("mysql:host=localhost;dbname=your_db","your_user","your_password");
// this line is important - throw an exception if there is an error
$dbconn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
function get_country( $dbconn, $code ) {
$res = $dbconn->prepare('SELECT country FROM `list_countries` WHERE `code`=? limit 1');
$res->execute( array( $code) )
$country = $res->fetch();
return $country['country'];
}

Related

Multi-parameterized SQL syntax invalid using WHERE AND

Below is the code in my model, I'm using Codeigniter, I'm sure there's a simple problem with it but I've been trying for a long time, any ideas?
<?php
class Users_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function checkLogin($username, $pass) {
$sql = "SELECT COUNT(*) FROM Users WHERE username=? AND password=?;";
$query = $this->db->query($sql, $username, sha1($pass));
if ($query -> num_rows() == 1) {
return True;
} else {
return False;
}
}
}
?>
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password=?' at line 1
If $this->db is a PDO object, than its query method doesn't allow you to use argument binding.
You will have to use a prepared statement. Your code would then look like:
$sql = "SELECT COUNT(*) as count FROM Users WHERE username=:user AND password=:pass";
$sth = $this->db->prepare($sql);
$sth->execute(array(':user' => $username, ':pass' => sha1($pass)));
$count = $sth->fetch(PDO::FETCH_COLUMN, 'count');
Today I found that the below worked, the parameters for the SQL statement just needed to be in a array.
$query = $this->db->query($sql, array($username, sha1($pass)));

Function to get mysql results in PHP 7

I'm struggling with the following problem. Some years ago, I've written a function to retrieve MYSQL results (multiple rows). Till PHP7, this code worked fine:
function MultipleRows($query)
{
global $dbhost, $dbname, $dbuser, $dbpass;
mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error! Couldn't <b>Connect</b>.");
mysql_select_db($dbname)
or die("Error! Couldn't <b>Select database</b>.");
$result = mysql_query($query)
or die("Error! Couldn't execute query.");
if(($result)&&(mysql_num_rows($result)>0))
{
return $result;
} else {
return false;
}
mysql_close();
}
Now in PHP7, this code doesn't seem to work anymore. After a lot of searching I came up with this as a replacement but unfortunately it doesn't work:
function MultipleRows($query)
{
$mysqli = new mysqli($dbhost, $dbpass, $dbuser, $dbname);
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
return $result;
$mysqli->close();
}
The function is meant to work with code like this:
$res_test = MultipleRows("SELECT id, name FROM table");
if($res_test)
{
while($res = mysql_fetch_array($res_test))
{
echo $res['id'].' '.$res['name'];
}
}
It's not a good option to rewrite the 'display code' (last fragment) because in that case I have to rewrite many lines in my website. Who can give me some help in this? Thanks in advance!
mysql extension has been dropped from PHP 7, after being deprecated in PHP 5.x.
You could rewrite function MultipleRows() using mysqli as follows:
function MultipleRows($query)
{
global $dbhost, $dbpass, $dbuser, $dbname;
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = $mysqli->query($query);
if ($result !== FALSE)
$result = $result->fetch_all(MYSQLI_ASSOC);
$mysqli->close();
return $result;
}
A few remarks:
it is not a good idea to use global variables ($dbhost, $dbuser, $dbpass and $dbname)
this way of handling database queries makes you vulnerable to SQL injection attacks

show tables get only the last name of table

I'm trying to show the name of table in my database. I write this code :
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList = $data[0];
}
return $tableList;
}
It give to me only the last table ?
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$tables = queryAll($db,$query);
print_r($tables);
Each time you are looping through the results, your are overwriting the variable tableList. Instead, you need to append to an array of results.
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
$tableList = array();
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
array_push($tableList, $data[0]);
}
return $tableList;
}
try this
`
function affiche_liste()
{$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList[] = $data[0];
}
return $tableList;
}
`
i hope it'll work...
here your array is overwitting every time...that's the reason you were getting the last table name....so you need to append to the existing array...

JOIN works in SQL not in Drupal

I'm trying to make a module for Drupal 7.x. At a certain point I want to use a sql query (JOIN). When I try the query in MYSQL it works. But when I want to try it in Drupal, the array is empty.
So I guess there is a difference between the sql query and the drupal query (mayby the implemantion is different).
SQL Query
SELECT * FROM friends
INNER JOIN users
ON friends.uid=users.uid
Drupal implementation
function project_myfriends(){
// Use database API to retrieve tasks
$query = db_select('friends', 'f');
$query->join('users', 'u', 'f.uid = u.uid'); // JOIN
$query->fields('u', array('name'))
->execute();
return $query;
}
/**
* Implements hook_block_view().
*/
function project_block_view($delta = ''){
switch ($delta) {
case 'project':
$block['subject'] = t('My Friends');
// Use our custom function to retrieve data
$result = project_myfriends();
$items = array();
var_dump($result);
foreach($result as $friend){
$items[] = array(
'data' => $friend->name,
);
}
// No tasks
if (empty($items)) {
$block['content'] = t('No friends.');
}
else {
// Pass data trough theme function
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
return $block;
}
Thx in advance
You forgot to fetch your result query:
$result = project_myfriends()->execute()->fetchAll();
var_dump($result);

mysql_num_rows() expects parameter 1 to be resource, boolean in joomla component

When I execute the function below query execute successfully but I get a warning above the result the query:
mysql_num_rows() expects parameter 1 to be resource, boolean
How do I fix this?
public function retrieve()
{
$id=JRequest::getVar('id');
$db =JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='$id' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$db->setQuery($sql);
$db->query();
$row = $db->getNumRows();
if($row == 1) {
return $db->loadAssocList();
} else {
$db = JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='$id' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";
$db->setQuery($sql);
return $db->loadAssocList();
}
}
Your code has several issues.
Never use unchecked/unvalidated request values, not even in examples!
Use the query builder.
Reduce coupling by a) setting the database in the constructor, which is done already in models, and b) retrieve the id in the controller.
You try to get all fields (*) from multiple tables, which have some column names in common. That will not work.
Have a look at JOINs.
This will work:
public function retrieve($id)
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car', '#__npco_namayeshgah', '#__npco_agahi'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_namayeshgah.id_namayeshgah = #__npco_agahi.id_namayeshgah');
$query->where('#__npco_car.car_id = #__npco_agahi.car_id');
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
if (empty($rows))
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car, #__npco_useragahi, #__npco_user'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_user.id_user = #__npco_useragahi.id_user');
$query->where('#__npco_car.car_id = #__npco_useragahi.car_id');
$db->setQuery($sql);
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
}
return $rows;
}
may be this is your issue..
Change your query as following
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='".$id."' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='".$id."' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";