Php pdo result array - php

I have a select to a database what should get a number and display it, but display just array
$sth = $conn->prepare("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $result;
What can I do to display that number?

You don't prepare anything so you don't need to use prepared statements just use query like this:
$result = $conn->query("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
foreach($result as $row)
echo $row['score'];

The previous answer is wrong, but not much.
When you're doing fetchAll(), you're getting all of the rows matching query from the database.
The answer is
$sth = $conn->prepare("SELECT score FROM people WHERE email=:email");
$sth->execute([':email' => 'gasd3z#yaho.com']);
$result = $sth->fetch(PDO::FETCH_ASSOC);
$sth->closeCursor();
echo $result['score'];
And don't forget that prepare() is for preparing statements, so you better want to have user data in query just like in my example. If you don't want to process any values in query, use query() or exec() instead.

You can print out arrays with print_r($result) or var_dump($result). Echoing only prints out the type.
Also, if you only need to print out a specific line, do it like echo $result['score'];

Related

Call to a member function fetch() on integer in

I have a problem with a simple pdo query here the query:
$NU=$connection->exec("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
Since I have no params to bind in the query is correct to use exec without prepare, and how can I fix this problem? (Call to a member function fetch() on integer in )
The exec() method only returns the number of rows effected. You probably want to use query() instead.
$NU=$connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
The query() statement will execute a single query and return a PDOStatement object you can fetch from or false on failure.
You need to use query http://php.net/manual/en/pdo.query.php , then you'll have a object with results you can work with.
Try this.
$NU = $connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$result = $NU->fetch();
echo $result['Total'];
What you are looking for is not exec but prepare. From the PHP doc: http://php.net/manual/en/pdostatement.fetch.php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

mysqli counting results and fetching them

Hello I have a prepared statement and I need to count the number of results I get. In order to do this I use store_result and num_rows
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
This code manages to get me the number of rows. The problem is that if I do this I cannot use fetch() on $rsActivation. If I use fetch and not use store_result I cannot get the number of rows.
How can I accomplish both things?
Thanks
SOLVED:
Turns out my problem was I was trying to fetch the results as an associative array. Instead I used bind_result to assign values to variables. Then I was able to use store_result and num_rows to get the count and after that I used fetch() together with the variables I assigned in bind_result.
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->bind_result($userId, $promo, $email);
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
while($rsActivation->fetch()){
echo "<p>". $userId ."</p>";
...
}
You can try using
...
$rsActivation->execute();
$results = $rsActivation->get_results();
$totalRows = $results->num_rows;
and you should be able to fetch using something like
$results->fetch_assoc(), $results->fetch_row(), etc.
Here's the doc for it: http://php.net/manual/en/class.mysqli-result.php

fetch the names of a the tables in mysql database with pdo and php

I have been attempting to get the table names from my mysql database with pdo and no matter what I try the only thing I get returned is the word Array for each table instead of the name.
I have tried all of the pdo fetch_* and one of them returned a 1 for each table while the others either return an error or the word Array. It does not matter which example below: $st or $rt
What am I missing?
Here is my code:
$sql = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_TYPE='BASE TABLE'";
$st = $db->query($sql);
$st->execute();
//$rt = $db->query("show tables");
//$rt->execute();
while($row = $st->fetch(PDO::FETCH_ASSOC)){
echo $row.'<br>';
}
Thanks in advance
Pete
Because this return a multi dimensional array. So you cannot outright echo it. Since you used PDO::FETCH_ASSOC flag, it will return an associative array which in turn you must access its proper index.
while($row = $st->fetch(PDO::FETCH_ASSOC)){
echo $row['TABLE_NAME'] . '<br/>';
}
Sidenote: I don't think $st->execute(); belong in there since this is not using a prepared statement. I think its safe to ditch that part.

How to make a select statement PDO and end up with $row['field']

I want to make a php PDO select statement and end up with the possibility to place $row['field'] wherever I want.
In normal mysql I would have done as following:
$row = mysql_fetch_array(mysql_query("SELECT * FROM table WHERE id = '1234'"));
And then I would be able to place $row['name'] in one place and $row['items'] in another.
How to do this?
$sth = $dbh->prepare("SELECT * FROM table WHERE id = '1234'");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
echo $row['field'];
The PDO counterpart to mysql_fetch_array is fetch(PDO::FETCH_BOTH). If you only care about an associative array, you can use fetch(PDO::FETCH_ASSOC)
I suggest you read up this short tutorial that will get you up and running with PDO rather quickly: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Categories