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;
Related
I have to fetch result in single row but I can't run multiple rows. How can I fix this?
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
I Got Result Like Wise This
{"ID":2,"Name":"Anju"}
But i need to get all user result .my code is here
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
$stmt->close();
return $result;
}
I got the error
Fatal error: Call to a member function fetch_array() on a non-object in line 5
The line is:
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))
my expecting result is
{"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bindValue(1, $id);
Try that way
And try to fetchAll instead of fetch_array
You could make following correction.
Change
$rows->fetch_assoc(MYSQLI_ASSOC)
to
$rows->fetch_assoc()
It should look like
if ($stmt->execute()) {
$rows = $stmt->get_result();
$result = array();
while ($row = $rows->fetch_assoc()){
$result[] = $row;
}
$stmt->close();
return $result;
} else {
return NULL;
}
Suggestion : Always specify the list of columns in your SELECT, which makes query execution faster.
Please read php manual
I am trying to get the results from a query which should get multiple results and display them all on the page. However it is not displaying any of the content. My guess is a mistake in my syntax for me loop. But I am unsure.
//query to find comments about this map
$query = "
SELECT
user_id,
comment
FROM map_comments
WHERE
map_id = :mapID
";
//query parameters
$query_params = array(
':mapID' => $_SESSION['mapID']
);
try
{
//execute query
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
//get all results
$comments = $result->fetchAll;
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
}
catch(PDOException $e)
{
die("failed to find comments");
}
foreach($comments as &$comment)
{
echo $comment;
}
You need parentheses after a function to call it.
$comments = $result->fetchAll;
should be:
$comments = $statement->fetchAll();
Also, the check for if ($result == FALSE) should be before this line. And you can't use mysql_error() if you're using PDO, you should use $statement->errorInfo(). Or you should enable PDO::ERRMODE_EXCEPTION on the connection, and the catch block will be invoked. You should then use $db->errorInfo() in the error message that it prints.
I am new to PHP prepare method, I need some help to use while loop in the following code.
Here is the query function
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt-> execute($bindings);
$result = $stmt->fetchAll();
return $result ? $result : false;
}
and the query
$home_team = query('SELECT home_team FROM premier_league
WHERE match_date >= :current_date
AND pre_selected = :pre_selected
ORDER BY match_date LIMIT 5',
array('current_date' => $current_date,
'pre_selected' =>$pre_selected),
$conn);
if (empty($home_team)){
echo "No Match Selected for Today.";
} else {
print_r($home_team);
}
How and where I use while loop for this query?
you don't need no while here
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt-> execute($bindings);
return $stmt->fetchAll();
}
$sql = 'SELECT home_team FROM premier_league WHERE match_date >= ?
AND pre_selected = ? ORDER BY match_date LIMIT 5';
$home_team = query($sql,array($current_date, $pre_selected), $conn);
foreach ($home_team as $row) {
echo $row['home_team']."<br>\n";
}
In else block
else {
print_r($home_team);
/* here
foreach ($home_team as $team) {
echo $team->home_team . '<br>';
}*/
}
PDOStatement implements Traversable so using fetchAll would be a overhead.
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt;
}
$home_team = query...;
foreach ($home_team as $row) {
echo $row['home_team']."<br>\n";
}
The idea of using a prepared query is to have the server parse the query once and create a query plan once. This is useful for queries that you execute repeatedly, only changing the parameter values.
Accordingly:
- the prepare should be done once.
- the execute should be done inside the loop.
If you are executing a query once in a while, then the prepare overhead is not worth it.
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.
I tried asking this before but didnt really get an answer so Ill try to rephrse it. I cant figure out how to pass the results of a multi line query to another function or page, especially using PDO. Would I execute the loop in the original function?
public function viewGallery(){
$pQuery = 'SELECT * FROM profiles WHERE userId = ?';
$viewGallery = $this-> _db ->prepare($pQuery);
$viewGallery ->bindParam(1, $id);
$viewGallery ->execute();
while ($get_row = $viewGallery ->fetch()){
$id = $get_row['id'];
}
}
then another page that accesses this:
//echo the results of viewGallery();
You need to return the results you want from viewGallery() then echo them on the other page.
You could return an array of results (ids by the looks of it) and then whiz through them with a while loop on your other page to display them
while ($get_row = $viewGallery ->fetch()){
$id = $get_row['id'];
$myBigArray[] = $id;
}
return $myBigArray;
Then on the other page just loop through and echo each result
Assuming that your SQL returns col1, col2 and col3
You can do the following to pass the results:
while ($get_row = $viewGallery ->fetch())
{
$col1 = $get_row['col1'];
$col2 = $get_row['col2'];
$col3 = $get_row['col3'];
someFunctionNameThatEchoesResults($col1, $col2, $col3);
}
You could also put all the results into an array and then pass it to the other function:
$resArray=array();
while ($get_row = $viewGallery ->fetch())
{
$col1 = $get_row['col1'];
$col2 = $get_row['col2'];
$col3 = $get_row['col3'];
$resArray[]=array($col1, $col2, $col3);
}
someFunctionNameTheShowsResults($resArray);
I would simply return the complete data set with fetchAll()
something like below
try {
$dbh = PDO(/* Connection Info */);
$query = "SELECT * FROM foo";
$stmt = $dbh->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}