Outputting a Select Query in PDO - php

I'm used to using BindParam() and since this is a SELECT query Param's are not related. Basically I'm trying to make a notification system that will check the database and if any of the rows' status is '0' then it would output all the rows information.
I have the following columns: id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status.
How would I make PDO put all the information it gathers from all rows with status='0' and put them into usable variables like: $id, $api, $request? Of course there could be more then one row with status='0' so maybe have the variables arrays and output like $id[0], $id[1] e.t.c.
PDO:
<?php
include('/cdn/global/db.php');
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
$dsn = "mysql:host=$host;dbname=$dbname";
$DBH = new PDO($dsn, $username, $password, $opt);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = 0");
$STH->execute();
echo "<p>The link is now in Queue, An admin will check the link soon!</p>";
# close the connection
$DBH = null;
######
?>

You can fetch them as objects(Also order by a field if you want the results in a specific order):
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = 0 ORDER BY id");
$STH->execute();
if($STH->rowCount()){
while($row = $STH->fetch(PDO::FETCH_OBJ)){
#Perform whatever operation you need on a single row
echo "$row->id, $row->api, $row->request, $row->apikey, $row->apiemail\n";
}
}

put them into usable variables like: $id, $api, $request e.t.c
There is no point in doing that. $row['id'] is no less usable but WAY more flexible. Although you can use extract() function to assign array members to corresponding variables.
of course there could be more then one row with status='0' so maybe have the variables arrays and output like $id[0], $id[1] e.t.c
This would make even less sense and nobody is doing it this way. Anyways, PDO won't make such variables for you. Instead, array of rows have to be used, like shown in other answers.

$value = 0;
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = ?");
$STH->execute(array($value));
$variable[] = $STH->fetchAll(PDO::FETCH_ASSOC);

Related

PHP PDO Service No Data

I have the below REST web service that I am using to get user information from User table:
$name = htmlentities($_GET["name"]);
$name = strtoupper($name);
$dbh = new PDO("oci:dbname= $dbhost", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("select * from Users where username =:name");
$sth->bindParam(':name', $name);
$sth->execute();
$result = array();
$result["User"] = $sth->fetchAll((PDO::FETCH_ASSOC));
print_r ($result); //returns no data
When I print out the results, no data is returned. If I hard code a username value instead of using :name, then data comes back:
$sth = $dbh->prepare("select * from Users where username ='TESTUSER'");
I am not sure what I am doing wrong with the binding of the variable that is causing the SQL to run incorrectly. I tried using bindValue and bindParam and still returns no data. I am not recieving any errors, just no data.
UPDATE: It looks like the syntax is correct. Is there anything on the Oracle side that would prevent a prepared statement from being run?
I figured out why data wasn't returning on the query. The database has the username field set as a CHAR(8) and usernames that were being passed only had 7 characters so it was failing. I need to append a blank space at the end of the string for it to match.

Select logged in user's ID using PDO

I am new to using PDO and was wondering how I would select the logged in user's id from my phpMyAdmin database.
My initialization file is...
session_start();
$_SESSION['user_id'] = 1;
$db = new PDO('mysql:host=localhost;dbname=project', 'root', '');
Here is my users table layout:
I'm assuming you want to get the users info where their id is the same as user_id
You might do something like this;
$query = $db->prepare('SELECT * FROM table WHERE id=:id');
//using bindParam helps prevent SQL Injection
$query->bindParam(':id', $_SESSION['user_id']);
$query->execute();
//$results is now an associative array with the result
$result = $query->fetch(PDO::FETCH_ASSOC);
I wasn't sure how user_id is set so I just used bindParam just in case.

PDO Prepared Statements and MSSQL databases not functioning correctly

I'm having a problem running prepared queries on a MSSQL database using PDO. I can connect to the database and run SELECT queries with no parameters, but now I'm trying to run a simple SELECT query with one parameter, :user. However, the code does not return any values, despite the fact that there definitely is a database row with that value in. Here's the code I'm using:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
I receive no output from the var_dump. I know that in the database there is a correct row, so I tried:
$stmt = $db->prepare("SELECT * FROM customer WHERE email_address = 'the#email.com'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
And yet still no value was returned. Am I doing something wrong with PDO? If I type this exact query into the query bar it runs.
you forgot to execute your query.
right after the paramter binding, put this code:
$stmt->execute();
Ok, I'm an idiot. Forgot to execute the query. Amended code for people in the same predicament:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

Player score update with PHP MySQL

I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work

This PDO statement is returning an integer instead of a string

In a class, I have some PDO:
$userFName = 'userFName';
include('dbconnect.php'); // Normally I'd store the db connect script outside of webroot
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('SELECT userFName FROM Users WHERE username = :uname AND password = :pword AND roleID = 1');
$stmt->bindParam(':uname', $this->user->username);
$stmt->bindParam(':pword', $this->user->password);
$stmt->bindColumn(4, $userFName, PDO::PARAM_STR);
$stmt->execute();
$familiar = $stmt->fetch(PDO::FETCH_BOUND);
$this->user->firstName = $familiar;
It's returning the ID in the first column instead of the VARCHAR contents in the 4th column. Any idea why?
When using PDO::FETCH_BOUND with fetch(), the method will not return a result record. Instead the value of the column should be available in the variable you have bound using $stmt->bindColumn() earlier.
So change your code to:
$stmt->bindColumn(1, $userFName, PDO::PARAM_STR);
$stmt->execute();
$stmt->fetch(PDO::FETCH_BOUND);
$this->user->firstName = $userFName; // <-- use the bound variable
However you won't need that bindColumn() call. You could simplify the code as this:
$stmt->execute();
$row = $stmt->fetch(); // uses PDO::FETCH_ASSOC by default
$this->user->firstName = $row['FName'];
There is too much code in your class. And one fault. To send a distinct query to get just one property from database, creating a distinct connection for this is a dead overkill.
Connection have to be moved away unconditionally and you must think of getting ALL user data with one query.
Proper code
function __construct($pdo) {
$this->pdo = $pdo;
// Normally you should include somewhere in a bootstrap file
// not in the application class
// and instantiate PDO in that bootstrap as well
// and only PASS already created instance to the class
}
function getUserFName() {
$sql = 'SELECT * FROM Users WHERE username = ? AND password = ? AND roleID = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($this->user->username,$this->user->password));
return $stmt->fetchColumn();
}

Categories