Issues reading arrays from mysql database when using PDO in php - php

I have the following code set to read and output a specific row from a database based on the criteria in the query statement below. When I try to log the output in console, however, I am only able to get one value and while it DOES exist in the database (as a key attribute), it is from the first row every time. I am not getting a row that matches the SQL criteria. Any ideas?
function getLoginInfo($email,$password){
global $db_user, $db_password, $db_host, $db_name;
if (isValidLogin($email,$password)){
$dbconn = connectToDB($db_user, $db_password, $db_host, $db_name);
$userInfoQuery = $dbconn->prepare("Select * from (Users as U inner join RegisteredUsers as R on U.UID = R.UID) where email = :email");
$userInfoQuery->execute(array(":email"=> 'derp#gmail.com'));
$results = $userInfoQuery->fetch(PDO::FETCH_ASSOC);
echo $results; //will return data in the form ["col1"=>rowdata,"col2"=>rowdata,..."colX"=>rowdata]
}
else{
return false;
}
}

You need to use a loop to fetch all the rows returned by your query:
while( $results = $userInfoQuery->fetch(PDO::FETCH_ASSOC) ) {
echo $results;
}
The documentation for the PDOStatement::fetch function says that the function "Fetches the next row from a result set", so it only returns one row. If the PDOStatement::fetchAll functions that will return the full result set.

Related

How can i make my each database field into a public variable in php?

I got my all database field by doing this query
"SHOW COLUMNS FROM admin"
but i am wondering how could i make each of them into a public variable!
and yes these variables will be in a class as i am doing OO PHP.
First, i need to take all field name from my database. Then I need to put them into a variable of a class.
This is how you use PDO to connect to database and execute queries:
try{
$db_host = '...'; // hostname
$db_name = '...'; // databasename
$db_user = '...'; // username
$user_pw = '...'; // password
$pdo = new PDO("mysql:host=".$db_host.";dbname=".$db_name, $db_user, $user_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//---------------------- QUERY -----------------------
$sql = "insert your query here";
//----------------------END QUERY -----------------------
$data = $pdo->query($sql);
//the next lines will convert the query results to an array
//containing the contents as single variables
$return = array();
foreach($data as $row){
$data = $row[0];
array_push($return, $row);
}
return $return;
}catch(PDOException $erro){
echo $erro->getMessage();
}
}
The $return variable will be an array of every row the query returned, and then you can access it as single variables.
You don't need to predefine the column names like this in order to access your database rows as objects.
Assuming you have established a PDO connection $pdo, you can execute a select query against a table and return your results as objects with public property names that correspond to the column names in your table.
$stmt = $pdo->query('SELECT * FROM admin');
while ($row = $stmt->fetchObject()) {
// each $row is an object with public properties matching the column names
// so you can do things with $row->column_a, etc.
// (obviously I don't know your actual column names)
}
It is very similar with mysqli:
$result = $mysqli->query('SELECT * FROM admin');
while ($row = $result->fetch_object()) { // ... }

PDO Query Showing No Results

So previously my queries were working fine. I usually use mysql but have recently changed to a pre-configured vps through godaddy. Last night I was trying to connect to my server via PDO, which is showing the connection is being made.
Next I was trying to select the data from a table using:
global $conn;
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetch();
All this shows on my website is Connection Successful, Array
It doesn't show any array information or anything, just the word "Array". The table has information in it, so it should be displaying the results. Any idea of what I am doing wrong?
You get Array because you are echoing an array. Fetch returns an array,
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
Since you are querying a full table you probably want all the results so you should loop the fetch and return that array.
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
while($row = $stm->fetch()) {
$returned_array[] = $row['name'];
}
return $returned_array;
Then iterate over this where ever you are using it for all the supplier names.
foreach(function_call_for_names() as $name) {
echo $name;
}
Alternately, you could use the PDO fetchAll function,
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll();
then
foreach(function_call_for_names() as $row) {
echo $row['name'];
}

loop mysql results in php outside of mysql query

i am having a bit of issue with a mysql query. for some reason i can echo all all associated rows inside of the mysql query but outside of the query it only return the last row. here is my code. any suggestions?
//Get all associated
$q=mysql_query("SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'");
while ($row = mysql_fetch_assoc($q)){
$act_name=$row['ACT_NAME'];
echo "$act_name<br>"; // This returns all rows fine
}
echo "$act_name<br>"; // This only return the last row. i would like to get all rows.
The only way that you can fetch all of the records is by using PDO or MySQLi. Here is an example:
$conn = new mysqli($hostname, $username, $password, $database);
$query = "SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'";
$results = $conn->query($query);
$resultArray = $results->fetch_all(MYSQLI_ASSOC);
As #esqew said, you need to stop using the mysql_* functions.

PHP Return ID[uniqueidentifier] after sql INSERT

Like the title says, I want the id of a row to be returned after INSERT to the database.
I've got 2 functions, one to make a connection to the database:
function db_connect() {
$host = "host";
$user = "user";
$pwd = "pwd";
$database = "db";
$con;
try{
$conn = new PDO( "sqlsrv:Server= ".$host." ; Database = ".$database." ", $user, $pwd);
}
catch(Exception $e){
die(print_r($e));
}
return $conn;
}
And one to insert a new record:
function setTiptile($name,$cols,$rows) {
$connect = db_connect();
$query = "INSERT INTO data(ID, name, cols, rows) VALUES(NEWID(),?,?,?)";
$stmt = $connect->prepare($query);
$stmt->bindValue(1, $name);
$stmt->bindValue(2, $cols);
$stmt->bindValue(3, $rows);
$stmt->execute();
return $connect->lastInsertId('ID'); // This should work, but doesn't, why?
}
I need the last function to return the ID of the inserted row, how should I do this?
EDIT:
Like the title says, the ID is an uniqueidentifier, no idea if that changes things.
EDIT: Ok, apparently I've got to use:$connect->lastInsertId('ID');, but this isn't returning anything at all. What can be the cause of that? The new row ís created in the database.
From the Manual:
Returns the ID of the last inserted row, or the last value from a
sequence object, depending on the underlying driver. For example,
PDO_PGSQL() requires you to specify the name of a sequence object for
the name parameter.
It should be something like:
return $connect->lastInsertId('yourIdColumn');
Use lastInsertId
$conn->lastInsertId();
(My) solution:
The parameter of lastInsertId() has to be the table name instead of the row name. Besides that, the table must have a row with the parameter IDENTITY checked, this is the row which is returned.
That brings to the conclusion that it's impossible to return a uniqueidentifier with lastInsertId() since this cannot have the parameter IDENTITY checked.
why not first do a select newid()
and then use that id in the insert

Use fetch_column and fetch(PDO::FETCH_ASSOC) together?

I will admit php is a new language to me.
Now I can get each of these working individually. In my prepare query SELECT * FROM... will allow my PDO fetch assoc while loop to work, but then fetch column doesn't work. And then I use SELECT COUNT(*) my fetch column works but then my fetch assoc doesn't.
So Is there away around this so both will work? As I need the fetch column to return how many rows there are as an integer value (1 or 0) to determine if the user has entered log in information. But then I need fetch column there to return back the string value of what is entered in my username section of the table in my database. So that I can use this information to check it against the input from the user to validate the user and password.
Thanks, here's my code. If you need it explained more clearly I'll have a go.
<?php
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inb271assignment'
);
$pdo = new PDO('mysql:host=' . $config['db']['host'] . '; dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$pdo->beginTransaction();
$username = $_POST['Username'];
$password = $_POST['Password'];
//Nicholas will be $dbUsername when fetch is working correctly.
$databaseusername = Nicholas;
if ($username&&$password)
{
$result = $pdo->prepare("SELECT COUNT(*) FROM members WHERE Username=?");
$result->execute(array($databaseusername));
$row = $result->fetchColumn();
if ($row!=0) {
while ($rows = $result->fetch(PDO::FETCH_ASSOC)) {
$dbUsername = $rows['Username'];
}
echo $dbUsername;
}
else
die("That user doesn't exist");
}
$pdo->commit();
}
catch(PDOException $pe)
{
echo($pe->getMessage());
}
?>
So currently I have SELECT COUNT(*) in there. So if I enter a username and password in my form on the page before it will return back as !=0 allowing the while loop to work. And the while loop normally works if I have SELECT *. But because I don't because I need the count it doesn't. So I can't retrieve the info I need from the database.
Use SELECT * FROM ... and PDO fetch assoc as normally and use $result->rowCount(); for returning all affected rows, which is equivalent with SELECT COUNT(*)
If you query with count(*) only to find out if there is a user with the given username in the database, then you don't need it. You could instead fetch the first row, and if it's empty then there is no user otherwise there is at least one. So you have implicitly your information.
$rowNum = 0;
foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
$rowNum = $rowNum + 1;
$dbUsername = $row['Username']; // btw after the loop you have only the name of the last row
}
if ($row>0) {
echo $dbUsername;
}
First of all you need to understand the meaning of each operator you are using.
And then use it smart, only when required, instead of adding whatever operators just because you've seen them used somewhere.
As a matter of fact, you don't need neither COUNT(*) nor rowCount(), nor while. Only one row is supposed to be returned. That's enough.
Transaction and try..catch also counts.
What you really need is just a few lines of code:
if (isset($_POST['Username']))
{
$sql = "SELECT * FROM members WHERE Username=? AND Password=?";
$result = $pdo->prepare($sql);
$result->execute(array($_POST['Username'],$_POST['Password']));
return $result->fetch();
// or do whatever you want with returned data
}
that's all
The example of login has one big flaw, it picks the password from the $_POST and queries it directly to mysql.
Which means that the password is in clear in the database.
To apply best practices, you should hash+salt the passwords and encrypt all personal data.
Good overview on how to do it:
http://www.sitepoint.com/hashing-passwords-php-5-5-password-hashing-api/

Categories