PHP PDO mysql_result() equivalent? - php

What would i use in PDO instead of old mysql_resul()?
function ib_uk_isvalid($db,$uk) {
try {
$sth = $db->prepare("SELECT count(*) FROM ib_userkeys WHERE value=:val");
$sth->bindParam(":val",$uk);
$sth->execute();
$numrows = $sth->fetchColumn();
if($numrows>=1) {
$sth2 = $db->prepare("SELECT * FROM ib_userkeys WHERE value=:val");
$sth2->bindParam(":val",$uk);
$sth2->execute();
$res = $sth2->fetchAll();
print($res[0]->type);
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
ib_uk_isvalid($db,1234)
Gives me error because it returns table instead of an object (which i need).

function ib_uk_isvalid($db, $uk) {
$query = $db->prepare('SELECT * FROM ib_userkeys WHERE value = :val LIMIT 1');
$query->bindValue(':val', $uk);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
return $row ? $row->type : 0;
}
... is how I'd write that. It may fix the problem.

Related

How to get single value in php instead of $stmt->fetchObject();

This is my function.
public function getOrderValue($order_id) {
$sql = "select SUM(OD.quantity * OD.product_sell_price) from table_order_details OD where OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$user = $stmt->fetchObject();
return $user;
} catch(PDOException $e) {
return NULL;
//echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
As there is only single column in query, How to return that value? Basically i want how to fetch SUM alone instead of returning an object $stmt->fetchObject();
You can use fetchColumn, but there is nothing wrong with returning $user->total or something similar.
public function getOrderValue($order_id) {
$sql = "SELECT SUM(OD.quantity * OD.product_sell_price) AS total FROM table_order_details OD WHERE OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$total = $stmt->fetchColumn();
return $total;
} catch(PDOException $e) {
return NULL;
}
}
Assuming you're using PDO, you could use fetchColumn
http://php.net/manual/en/pdostatement.fetchcolumn.php

Using PHP and MySQL, how do you send a variable into a WHERE... IN clause?

The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}

please How to convert mysql query to pdo in my code?

my code PHP in mySQLquery to unique product id function
function kode($tabel, $inisial){
$struktur = mysql_query("SELECT * FROM $tabel");
$field = mysql_field_name($struktur,0);
$panjang = mysql_field_len($struktur,0);
$qry = mysql_query("SELECT MAX(".$field.") FROM ".$tabel);
$row = mysql_fetch_array($qry);
if ($row[0]=="") {
$angka=0;
}
else {
$angka = substr($row[0], strlen($inisial));
}
$angka++;
$angka =strval($angka);
$tmp ="";
for($i=1; $i<=($panjang-strlen($inisial)-strlen($angka)); $i++) {
$tmp=$tmp."0";
}
return $inisial.$tmp.$angka; }
how to convert this code to php pdo? please help me..
Here is a standard snippet I use for PDO:
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
$date = reformatDate($_POST['date']);
$sql="SELECT * FROM order_items WHERE date_start = :date";
$sth = $dbh->prepare($sql);
$sth->bindParam(':date', $date, PDO::PARAM_STR, 10);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
This example should point you in the right direction, but you need to do the heavy lifting.
Update
This would also be acceptable.
$madeupstring = "Mk9285425";
$sql="SELECT * FROM order_items WHERE product = :whatever";
$sth = $dbh->prepare($sql);
$sth->bindParam(':whatever', $madeupstring);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
You could also do this:
$sql="SELECT * FROM order_items WHERE product = 'Mk9285425'";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

PDO fetchAll not returning all rows

So I am trying to get multiple things from database. It is not working.
In my functions file I have:
public function getAllMultiple($username, $course) {
foreach ($course as $key) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
return $query->fetchAll();
}
}
In my feed function I have:
$array = $course->getAllAsMember($username);
print_r($course->getAllMultiple($username, $array);
I have two courses. I have a drug course and a class course. Unfortunately, it is only returning the drug course. Is there anything I'm doing wrong?
To expand on my comment, you can do something like:
public function getAllMultiple($username, $course) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$results = array();
foreach ($course as $key) {
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
results[] = $query->fetchAll();
}
return $results;
}
You should also improve your error handling, for example by putting everything within a try - catch block instead of just a part of it.
The return bit of your function stops execution of the function and returns the value. If you want to return both results of the queries you execute, you need to assign them to an array, and then return that:
public function getAllMultiple($username, $course) {
$return = array(); //initialize the array before the foreach function
foreach ($course as $key) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
$return[] = $query->fetchAll(); //collect the results
}
return $return; //return the array
}
Hopefully my comments are self-explanatory.

help with making this mysql query into a PDO query

I have been using this for a while, but have since then upgraded to PDO instead of mysql queries. But I can't seem to get this particular snippet to work at all.
$query = mysql_query ($sql) or die (mysql_error());
while ($records = #mysql_fetch_array ($query)) {
$alpha[$records['alpha']] += 1;
${$records['alpha']}[$records['id_clients']] = array(
$records['first_name'], //item[0]
);
}
I have tried this
while ($records = $this->db->fetch_row_assoc($sql)) {
$alpha[$records['alpha']] += 1;
${$records['alpha']}[$records['id_clients']] = array(
$records['first_name'], //item[0]
);
}
and my PDO code is
public function query($statement)
{
return self::$PDO->query($statement);
}
public function fetch_row_assoc($statement) {
self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try
{
$stmt = self::$PDO->query($statement);
$result = $stmt->fetch();
return $result;
}catch(PDOException $e){
echo $e->getMessage();
}
return false;
//return self::$PDO->query($statement)->fetch(PDO::FETCH_ASSOC);
}
The query function works, but I have introduced my fetch_row_assoc function in hopes that I can do that same thing with mysql_fetch_asso.
$sql = "SELECT
SUBSTRING(`last_name`, 1, 1) AS alpha,
SUBSTRING(`middle_name`, 1, 1) AS subMiddleName,
`id_clients`,
`type`,
`first_name`,
`middle_name`,
`last_name`,
`address`,
`primary_number`,
`secondary_number`,
`home_number`,
`office_number`,
`cell_number`,
`fax_number`,
`ext_number`,
`other_number`,
`comments`
FROM `clients`
WHERE `user_id` = 1
AND `is_sub` = 0
AND `prospect` = 1
ORDER BY `last_name`";
Try this:
public function query($statement)
{
return self::$PDO->query($statement);
}
public function fetch_row_assoc($statement) {
self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try
{
$stmt = self::$PDO->query($statement);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetch();
return $result;
}catch(PDOException $e){
echo $e->getMessage();
}
return false;
}

Categories