I have a pdo function that fetches usernames and user ids from the database. When I run the function i get different results.
print_r gives
Array ( [ID] => 58 [username] => abdullatif )
and foreach gives me
5-5a-a
There is one row that matches the pdo query in the database.
public function getUserCredentials($userName, $password){
$this->db = new Dbpdo_Database();
$this->db->connect();
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT
ID
FROM
administrators
WHERE
username = :username
AND
user_password = :password
LIMIT 1");
$stmt->bindParam(':username', $userName, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
}
$stmt->execute();
/*** fetch the results ***/
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
/*** close the database connection ***/
//$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
$results = $mydb->getUserCredentials($userName, $password);
foreach ($results as $row){
echo $row['ID'].'-'.$row['username'];
}
print_r($results);
Any hints as to whats wrong would be much appreciated. Thanks in advance.
Your $results array is one-dimensional - it has an ID and a username. Your foreach is looking for a two-dimensional array, with each row containing an ID and a username. Change it to:
foreach($results as $key => $value) {
echo $key . '-' . $value;
}
and you should get:
ID-58
username-abdullatif
Related
I got this simple PHP code to print a Column from a database and it isn't working unfortually. Any ideas on what to do right?
I've tried to work on the while loop I have in the if statement but no luck
What im trying to get array to print like :
<?php
$input = $_POST['input'];
$servername = "localhost";
$username = "hawk_manager";
$password = "hawk_eyes";
try {
$pdo = new PDO("mysql:host=$servername;dbname=HawkCenter", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if ($input == "RoomNumber") {
$query = 'SELECT RoomNumber FROM rooms';
$statement=$pdo->prepare($query);
$statement->execute();
$roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
while( $roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC)){
echo "{$statement['RoomNumber']}";
}
}
$conn = null;
?>
You are doing it wrong, it should be
1. Selecting multiple rows
$data = $pdo->query("SELECT RoomNumber FROM rooms")->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo $row['RoomNumber ']."<br />\n";
}
2. Prepared Statements::
$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms WHERE id=?");
$stmt->execute([$id]);
$user = $stmt->fetch();
OR
$stmt = $pdo->prepare("$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms LIMIT :limit, :offset");
$stmt->execute(['limit' => $limit, 'offset' => $offset]);
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row['RoomNumber']."<br />\n";
}
i'm trying to get user information from database, but it keep giving me an empty array.
code : i.stack.imgur.com/Op4HB.png
$information = array();
$user = 'admin';
$myuser = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($info = $myuser->prepare("SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* get result */
$result = $info->get_result();
/* bind result variables */
$info->bind_result($information['id'],$information['username'],$information['email'],$information['birthday'],$information['first_name'],$information['last_name'],$information['gender'],$information['profile_picture'],$information['cover_picture']);
$info->fetch();
$rows = $result->num_rows;
$info->close();
}
if (!$rows) {
redirect('http://example.com/');
} else {
print_r($information);
}
this is what i get :
can someone help me in this ? i use mysqli all the time but i don't know what went wrong this time.
thanks.
Try this
Fetch & display the results inside the while loop
if ($info = $myuser->prepare("SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* get result */
$result = $info->get_result();
/* bind result variables */
$info->bind_result($information['id'],$information['username'],$information['email'],$information['birthday'],$information['first_name'],$information['last_name'],$information['gender'],$information['profile_picture'],$information['cover_picture']);
$rows = $result->num_rows;
}
if (!$rows) {
redirect('http://example.com/');
} else {
while ($info->fetch()) {
print_r($information);
}
}
EDIT
if ($info = $myuser->prepare("SELECT email FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* bind result variables */
$info->bind_result($email);
$info->fetch();
printf("%s \n", $email);
}
i fixed it myself
i found the answer at http://php.net
thanks anyways !
<?php
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $user);
$stmt->execute();
$res = $stmt->get_result();
$rows = $res->num_rows;
$information = $res->fetch_assoc();
if($rows == 0 ) {
redirect("http://example.com");
}
print_r($information);
?>
PS: account.php is being required by index.php so it gets '$user' from there
output
Array ( [id] => 15 [username] => admin [email] => admin#theboat.tn [bd] => 2017-02-07 [firstname] => Saif [lastname] => Eddin [gender] => male [ppicture] => 1f4c1b47a3910039e60851c453ae4d80_a.jpg [cpicture] => default_c.jpg )
I have this in my PHP:
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$selected_client = $_POST['client'];
$sql = 'SELECT `cohort_id`,`cohort_name`, `cohort_description` FROM table_cohorts where client_id = :client';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) );
$stmt->execute(array(':client' => $selected_client));
foreach ($stmt as $row){
$result = $stmt->fetchAll();
}
header('Content-type: application/json');
echo json_encode($result);
This returns something that's ALMOST correct. It returns all the relevant, expected rows from my db table except for the first one. I'm guessing that I'm overwriting that somehow, but not sure where it's going wrong.
Unsure of why you've got a foreach loop in there. You'd use a foreach on $result to loop through the rows when what you want here is all the rows so you'd drop the loop.
foreach ($stmt as $row){
$result = $stmt->fetchAll();
}
and keep just this part.
$result = $stmt->fetchAll();
Just use
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
and get rid of the foreach loop.
I'm using PDO for the connection to my database. This is the code I'm using:
<?php
session_start();
if (ValidarCreacionUsuario($_POST)) {
if (ValidarNoEmpty($_POST)) {
$connection = new PDO('mysql:host=localhost;dbname=dbname', "dbuser", "dbpass");
$sql = 'SELECT * FROM users WHERE username = :username AND password = :password';
$statement = $connection->prepare($sql);
$statement->bindParam(':username', $_POST['username'], PDO::PARAM_STR, 12);
$statement->bindParam(':password', $_POST['password'], PDO::PARAM_STR, 30);
$result = $statement->execute();
And then, I want to catch the value of the 'sex' column and the value of the 'id' column in my database, so, I think I have to use the fetchAll() or something like this, but I don't know how to use it or if I have to use it.
So, what do I have to use?
Thanks.
something like this will show you what is available to you to use in an associative array (key and value)
$sql = "SELECT * FROM users... etc";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.