help with making this mysql query into a PDO query - php

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;
}

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

PDO do not work when i check ip

Today i tired pass from the mysql connection to PDO. And i met a problem.
require('config.php');
function GetAll($query, $params) {
global $db;
try {
$sth = $db->prepare($query);
}
catch (PDOException $e) {
return null;
}
try {
$sth->execute($params);
}
catch (PDOException $e) {
return null;
}
$result = $sth->fetchAll();
return $result;
}
if ($fetch = GetAll("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`=':ipcheck'", array(":ipcheck" => $iptocheck))) {
$resultx = $db->prepare("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
$resultx->execute();
while ($rowx = $resultx->fetch()) {
;
}
$loginattempts_total = $rowx['failedattempts'];
echo "$loginattempts_total";
if ($loginattempts_total > $maxfailedattempt) {
header(sprintf("Location: %s", $forbidden_url));
exit;
}
}
this is my script. in PDO and his don't work. when my ip is banned should not see, but i see the page. PLEASE HELP ((

PHP PDO mysql_result() equivalent?

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.

PDO Multi-query "SQLSTATE[HY000]: General error"

I'm still learning PDO so I might of missed something but basically I'm trying to insert a row into a table and then select the generated id.
I'm not sure if it likes both queries in one pdo statement. Here is the code I'm using to execute the SQL.
public function ExecuteQuery($sql, $params = array())
{
if($this->_handle == null)
$this->Connect();
$query = $this->_handle->prepare($sql);
foreach($params as $key => $value)
{
if(is_int($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_INT);
}else if(is_bool($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_BOOL);
}else if(is_null($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_NULL);
}else{
$query->bindValue(':'.$key, $value, \PDO::PARAM_STR);
}
}
$query->execute();
$x = $query->fetchAll(\PDO::FETCH_ASSOC);
var_dump($x);
return $x;
}
This function is part of a database class, $this->_handle is the PDO object.
public function Connect()
{
try {
$this->_handle = new \PDO('mysql:host='.$this->_host.';dbname='.$this->_database, $this->_username, $this->_password);
$this->_handle->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
And the SQL I'm running is this:
INSERT INTO `users` (`Username`, `Password`, `PasswordSalt`, `Email`, `IsAdmin`, `LoginAttempts`, `LastLogin`, `LastLoginAttempt`, `Created`) VALUES (:username, :password, :passwordsalt, :email, :isadmin, :loginattempts, :lastlogin, :lastloginattempt, :created); SELECT LAST_INSERT_ID() as 'id'
The user is created and is there in the users table but it errors after that.
Can anyone see what am doing wrong? :)
Cheers!
I'm pretty sure the mysql driver for PDO (maybe mysql itself?) does not support multi-query prepared statements.
Instead of SELECT LAST_INSERT_ID() in your query, use Conexion::$cn->lastInsertId() after your $query->execute()
I think this is correct:
function ExecuteQuery($sql, $params = array())
{
if(Conexion::$cn== null)
Conexion::Connect();
$paramString="";
foreach($params as $k=>$v)
{
$param = " :".$k." ,";
$paramString .= $param;
}
$sql.=substr($paramString,0,-2);
$query = Conexion::$cn->prepare($sql);
foreach($params as $key => $value)
{
echo "entro";
$query->bindParam(":".$key, $value);
}
$query->execute();
$x = $query->fetchAll(\PDO::FETCH_ASSOC);
var_dump($x);
return $x;
}
public function Connect()
{
try {
$dns='dblib:host='.Conexion::$server.";dbname=".Conexion::$db.";";
Conexion::$cn = new \PDO($dns, Conexion::$user, Conexion::$passw);
Conexion::$cn->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

Converting MySQL connector to PDO

After taking some advice from people on here in a previous thread, I'm trying to convert my MySQL to PDO, but am running into some issues.
Here is my original MySQL connection class:
class DbConnector {
public static function getInstance() {
static $instance = null;
if ($instance === null) {
$instance = new DbConnector();
}
return $instance;
}
protected $theQuery;
private $link;
function DbConnector() {
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
public function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
public function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
public function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
public function fetchArray($result) {
return mysql_fetch_array($result);
}
public function close() {
mysql_close($this->link);
}
public function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
public function last_id($query) {
return mysql_insert_id($query);
}
}
Here is the function that I'm writing:
function getRandomSubmission() {
global $db;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$query = $db->find("
SELECT
*
FROM
`submissions`
WHERE id = '{$submission_id}'
LIMIT 1
");
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
if($query) {
return $query[0];
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
}
Here is the PDO connector:
$host = 'localhost';
$username = '';
$pass = '';
$db = '';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $username, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
Here is what I've tried to convert it to, but it's just plain wrong. I think I need to be returning a PDO associative array in the 2nd if statement, but am not sure.
function getRandomSubmission() {
global $dbh;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
WHERE
`id` = ?
LIMIT 1
');
$stmt->bindParam(1, $submission_id, PDO::PARAM_INT);
$stmt->execute();
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
if($stmt) {
return $stmt[0];
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
}
The original one works as intended, however (I realize I left the connection details blank).
You need to call fetch method of the PDOStatement object:
return $stmt->fetch()
Read about the fetch style, really you don't need FETCH_BOTH ;-)

Categories