I am trying to obtain the user id from my database, using the query bellow, to insert it somewhere else. I am new to php and sql so I can't really spot what's wrong. The result I get on var_dump() is object (SQLite3Result)#4 (0) { } - I only used this for testing. I tried using fetchArray() but it still got me nothing. The database works alright, I used it for other things.
require 'database.php';
$db = new Database();
$email = $_POST['member'];
$list = $db->prepare('SELECT userid FROM users WHERE (email = :email)');
$list->bindValue(':email', $email, SQLITE3_TEXT);
$q = $list->execute();
var_dump($q);
Thanks for any help!
Here is what you can do:
<?php
class UserDB extends SQLite3
{
function __construct()
{
$this->open('test.db');
}
}
$db = new UserDB();
$stmt = $db->prepare('SELECT * FROM users where email = :email');
$stmt->bindValue(':email', 'user1#example.com', SQLITE3_TEXT);
$result = $stmt->execute();
var_dump($result->fetchArray());
Then you can update the bindValue method call with the email variable.
For the sqlite3 db I created it using the following commands:
$ sqlite3 test.db
CREATE TABLE USERS (
ID INT PRIMARY KEY NOT NULL,
EMAIL TEXT NOT NULL
);
INSERT INTO USERS VALUES(1, 'user1#example.com');
.quit
Then you can use that with my code.
Related
I need some help. I have some nested SELECT statements that get the user's ID then use that ID to search another table in MySQL. I have a foreach() loop that uses the user_id from the first query to create a folder for the user if there isn't one in the filesystem. Then I used bindParam() to assign it a variable and use it in another query to get the user's name. However, it throws and exception saying 'Call to a member function bindParam() on null in C:\foo\bar\foobarscript.php on line 29'. Here's my code up until the break...
try {
$con = new PDO("mysql:host=$dbname;dbname=$db", $user, $pass);
//Set the PDO error mode to exception
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$stmt = $con->prepare("SELECT user_id
FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetchAll();
foreach($res as $row) {
$uid = $row['user_id'];
$filename = './reports/'.$uid.'';
if(!file_exists($filename)) {
if(!mkdir('./reports/'.$uid)) {
die('Failed to create folders..');
}
}
$stmt2->bindParam(':uid', $uid); //<--- Code breaks here
$stmt2 = $con->prepare("SELECT CONCAT(fname,' ',lname) as fullname FROM users WHERE user_id = :uid");
$stmt2->execute();
$fullName = $stmt2->fetchAll();
$userArray[] = array_fill_keys($uid, $fullName);
$stmt2->closeCursor();
}
I have searched up and down and tried rewriting it, debugging piece by piece. Everything works fine until I put it all back together and I get this error again. I really appreciate any help!
Edit: I have even tried removing the assigned variable and binding like:
$stmt2->bindParam(':uid', $row['user_id']);
from config.php
<?php
global $dbh;
$dbname = 'memberdb';
try {
$dbh = new PDO("mysql:host=localhost", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbname = "`".str_replace("`","``",$dbname)."`";
$dbh->query("CREATE DATABASE IF NOT EXISTS $dbname");
$dbh->query("use $dbname");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql ="CREATE TABLE IF NOT EXISTS $member (
mem_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40) NOT NULL,
password VARCHAR(40) NOT NULL);" ;
$dbh->exec($sql);
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
} catch(PDOException $e) {
}
?>
This is my function of new user when the user is registered using a registered button.
How to make this kind of function run only one, when the database is created and only.
I will need to put defined value for each input but i didnt not change it yet
UPDATE
The code i used is above my prob is still the same when i reload the index.php the query runs again making double entry..what i want is that when the database is create the query will run and when loaded the database is not created again so i want the query to not run again to avoid double entry.
$stmt = $dbh->prepare("SELECT * FROM member") ;
$stmt->execute();
$count = $stmt -> rowCount();
echo $count;
if( $count == 00 ){
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
}
i only have one more question why is it sometimess the echo for count is 3 and sometimes its 33 its like the query is run twice please clear this out...this worked but maybe just maybe there are incorrect logic here please feel free to edit to make it perfect.
I have a table in oracle (11g xe) 'bill' which has a structure like below:
key_id number(10),
bill_no number(10),
bill_date date,
cons_id_no varchar(10),
cons_no char(15)
I am connecting to the database using PHP::PDO like below:
public function findByConsumerNumber($consumerNumber) {
$pdo = new \PDO('oci:dbname=/localhost:1521/xe','kaushik','123');
$stmt = $pdo->prepare('SELECT * FROM bill WHERE cons_no = :cons_no');
$stmt->bindParam(':cons_no',$consumerNumber);
$stmt->execute();
return $this->findCollection($stmt->fetchAll());
}
But on executing I am getting 0 results. But when I change the code as follows, I am getting results:
public function findByConsumerNumber($consumerNumber) {
$pdo = new \PDO('oci:dbname=/localhost:1521/xe','kaushik','123');
$stmt = $pdo->prepare("SELECT * FROM bill WHERE cons_no = '" . $consumerNumber . "'");
$stmt->execute();
return $this->findCollection($stmt->fetchAll());
}
I am not able to find the actual problem.
Note: when I try to find results based on cons_id_no as in the first method given above, I am getting results.
You have a spelling mistake : consumberNumber should be consumerNumber
You should look into Dependency injection, initializing a db connection every time a method is called is crazy.
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();
}
//This is my function in retrieving the id of the user base from its email and pass. this is for functions.php
function getID($email,$pass)
{
$pdo = new PDO(connection here);
$stmt = $pdo->prepare('SELECT id user where email = :email and pass = :pass LIMIT 1');
$stmt->execute(array(':email'=>$email, ':pass'=>md5($pass)));
$result = $stmt->fetch();
return $result['id'];//Is this the right way of returning a value from a fetch value?
}
//this is for user.php.
include 'function.php';
session_start();
$_SESSION['id'] = getID($_POST['email'],$_POST['pass']);
Is this the right way of retrieving it? but i do not get any values from it. Need help thanks!
Your query is missing a FROM.
SELECT id FROM user WHERE email = :email AND pass = :pass LIMIT 1