PHP PDO Select result showing as array - php

I am trying to get the (float) value from a database, but when I print the result it is showing as 'Array' instead of the value (20).
Here is the code:-
public static function getTourFare($fieldTour) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT Fare FROM tbltours
WHERE TourName = '$fieldTour'";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$stmt->closeCursor();
print_r($result[0]);
return $result;
$dbh = null;
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
}
I know it is only selecting one value and shouldn't return an array of values. I believe the issue is $stmt->fetchAll();, but I'm not quite sure what this needs to be changed to?

From fetchAll() documentation
PDOStatement::fetchAll() returns an array containing all of the
remaining rows in the result set. The array represents each row as
either an array of column values or an object with properties
corresponding to each column name.
You can use fetchColumn() to fetch just a string result.

Related

Get ASSOC array with PDO without using prepared statement

I'm using an internal switch to determine the sort order of my results and have just discovered that you can't use PDO to bind certain params (like selecting a table or specifying a sort order) in this way.
So I'm now trying to return my results without binding using ->query like this (ignoring the sort part for now) :
$results = $db->query("SELECT * from tracks WHERE online = 1", PDO::FETCH_ASSOC);
But when I print_r($results) I'm just getting the PDO object statement back :
PDOStatement Object
(
[queryString] => SELECT * from tracks WHERE online = 1
)
What am I doing wrong here?
Here is my PDO connection :
protected static function getDB()
{
static $db = null;
if ($db === null) {
$dbhost = getenv('DB_HOST');
$dbuser = getenv('DB_USER');
$dbpass = getenv('DB_PASS');
$dbname = getenv('DB_NAME');
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",
$dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
return $db;
}
the statement needs to be executed ...
$stmt = $db->query("SELECT * from tracks WHERE online = 1");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
passing it as second argument should also work:
$stmt = $db->query("SELECT * from tracks WHERE online = 1", PDO::FETCH_ASSOC);
$data = $stmt->fetchAll();
or as one-liner:
$data = $db->query("SELECT * from tracks WHERE online = 1")->fetchAll(PDO::FETCH_ASSOC);
there's also:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
PDO::query manual shows you how to work with results, returned by query method:
$results = $db->query("SELECT * from tracks WHERE online = 1", PDO::FETCH_ASSOC);
foreach ($results as $row) {
print $row;
}

cant catch assoc array, confirmed that there is results there but wont select and show

This could be a simple syntax error but I've tried every I know how. I have a database class for selecting data
<?php
/* this script is for creating a class to connect to the database */
include "includes/config.php";
class database {
protected static $connection; // variable to hold the mysqli connection
protected function connect(){
if (!isset(self::$connection)){ // if the connection variable is not set
self::$connection = new mysqli(SERVER_NAME, USERNAME, PASSWORD, DB_NAME); // set the connection
}
if (self::$connection === false){ //in case connection failed return false
return false;
}
else {
return self::$connection; // returns the connection
}
}
protected function query($query){ // public function to take a sql query
$connection = $this->connect(); // calls the connect function to create a connection to the database
$result = $connection->query($query); // puts the query into the result variable
return $result; //returns the result
}
public function select($query){
$rows = array();
$result = $this->query($query);
if($result === false){
return false;
}
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
public function error(){
$connection = $this->connect();
return $connection->error;
}
}
?>
I have instantiated this in index.php. I made a query and passed it to the select method then ran an if statement to say that if the size of the result is greater than or equal to 1 then echo query successfully. Here's where I keep screwing up. I'm trying to just print out the value of first_name but no matter what way I try it won't print. is this a 2d associative array?
<?php
include 'view/header.php';
include 'includes/connect.php';
$db = new database();
$sql = "SELECT `first_name`, `last_name` FROM `pratts_db`
WHERE `first_name` = `clive`;";
$result = $db->select($sql);
if (sizeof($result) >= 1){
echo "query successful";
echo "<p>{$result[`first_name`]}</p>";
}
include 'view/footer.php';
?>
I've tried it with different quotation marks, tried selecting 0 position then the first_name and it doesn't work. what am I missing?
$result is a 2-dimensional array. Each element of the array is a row of results, and the columns are elements of those associative arrays.
So you need to loop over the results:
foreach ($result as $row) {
echo "<p>{$row['first_name'}</p>";
}
If you only need the result from the first row (e.g. if you know the query can't match more than one row), you can index it instead of looping:
echo "<p>{$result[0]['first_name']}</p>";
You also have the wrong kind of quotes around first_name in
$result[`first_name`]
They should be single or double quotes, not backticks. And in the SQL, you should have single or double quotes around clive, unless that's a column name. See When to use single quotes, double quotes, and back ticks in MySQL

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

PDO fetchAll() returns an empty array

in my code im trying to get data from my db with PDO and bind params but i keep on getting empty array, this is my code :
try{
$pdo =new PDO('mysql:host=localhost;dbname=***', '***','***');
$pdo->setAttribute(pdo::ATTR_ERRMODE,
pdo:: ERRMODE_EXCEPTION);
$pdo->query('set names "utf8"');
}
catch (PDOException $e) {
die('error connectin database');
}
$table = 'products';
$column = 'id';
$niddle = '70';
$sql = "SELECT * FROM `{$table}` WHERE ";
$sql .= ":column LIKE :niddle";
$pre = $pdo->prepare($sql);
$pre->bindParam(':column', $column ,PDO::PARAM_STR);
$pre->bindParam(':niddle', $niddle, PDO::PARAM_STR);
$result = $pre->setFetchMode(PDO::FETCH_ASSOC);
$pre->execute();
print_r($pre->fetchAll());
there is no exeption thrown, what could be the problem?
You should not bind the column name as a prepared statement parameter string as it will quote the column name. Do like you do with the table name just use it-- after whitelisting it.

Can't get array from PDO query

i'm trying to get an array from a SQL query using pdo, what i send to the method it's for example $connection->selectFrom('Person',array(1,2));
when i try to get the results it returns an empty array, here is my code:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
// HERE I GET ALL THE COLUMN NAMES FROM THE TABLE I RECEIVE
$columns = $this->getColumnNames($table);
$finals = array();
// IN THIS CICLE I GET THE COLUMNS THAT MATCH THE INDEXES I RECEIVE
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
// FROM HERE I GET THE QUERY STATEMENT WICH IS SELECT column1,column2 from $table
$query = $this->getSelectSQL($table, $finals);
// ALL OF THE ABOVE WORKS BUT HERE IT STOPS WORKING
$results = $pdo->query($query);
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Thanks to #Cymbals for your answer, the final code ended up like this:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
$columns = $this->getColumnNames($table);
$finals = array();
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
$query = $this->getSelectSQL($table, $finals);
$query.= " WHERE Available = 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt ->fetchAll();
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Try this after getting the query, prepare and execute it
$stmt = $pdo->prepare($query);
var_dump($stmt);// if the prepare fails or sql query is messed up it will give false
$results = $stmt->execute();
return $results;

Categories