my intention is to make a live validation , which i found a side that tutorial but they are using old sql , i wanted to use my sql PDO , but i cant make it work , even my database having the same name , it still say ok.
how do i make it work , before you check my code , please look and download the link to check it out, thank.
download from here:
Please Check This Link
my code(i changed some to PDO but still wont work)
dbConnector.php
<?php
class DbConnector {
var $link;
function DbConnector(){
try{
$this->link = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '123456');
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->link->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
}catch(PDOException $e){
die("this is not connected");
}
}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
try{
$this->link->prepare($query);
}catch(PDOException $e){
die("fail to prepare");
}
return $this->link;
}
}
?>
check.php
<?php
include("dbConnector.php");
$connector = new DbConnector();
$username = trim(strtolower($_POST['username']));
$query = "SELECT air_users FROM USER_NAME WHERE username = ? LIMIT 1";
$result = $connector->query($query);
$result->execute(array($username));
$num = $result->rowCount();
$num = $result->fetch();
echo $num;
// mysql_close();
?>
i dont have any error , but still it wont work. thank for helping out.
You need to return the returned value of $this->link->prepare($query); not the $this->link itself. To make it work, rewrite your query this way:
function query($query) {
return $this->link->prepare($query);
}
I don't think that the $username variable is been interpreted on the string, as you have it.
"SELECT users FROM USER_NAME WHERE username = :username' LIMIT 1";
...
execute(array(':username' => $username));
and on the query method call prepeare like:
$this->link->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
or
"SELECT users FROM USER_NAME WHERE username = ? LIMIT 1";
...
execute(array($username));
And the prepare method should be call like you have it on your example:
$this->link->prepare($query);
And on the query method you return the $query or the string. You should return the instance or execute in the query method.
function query($query) {
try{
$this->link->prepare($query);
}catch(PDOException $e){
die("fail to prepare");
}
return $this->link;
}
See
Related
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
I'm attempting to use functions to get certain data from database. For example, I want to get info from an user with ID 1.
try {
$connection = new PDO("mysql:host=localhost;dbname=database", "root", "password");
}
catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function getUser($id) {
global $connection;
$query = $connection->prepare("SELECT * FROM accounts WHERE ID = '$id'");
$query->execute();
while($row = $query->fetch()) {
echo $row['playername'];
$user[] = $row;
}
}
And then in my index.php.
include 'inc/db.php';
getUser("1");
foreach($user AS $user) {
echo $user['ID'];
}
The first echo works, I get the username displayed, but the foreach doesn't echo anything. I tried to var_dump($user); but ended up getting NULL.
You need to have:
function getUser(...) {
...
$user = array();
while(...) {
$user[] = $row;
}
return $user;
}
And then in your main code:
$users = getUser(1);
foreach($users as $user) { .... }
Right now you're defining local variables and then not returning them, so they're lost when the method exits. And then not capturing any possible returned values anyways, making your code basically pointless.
Your problem is that you are writing too much code. PHP can't process so much, chokes and dies.
All you actually need is
$pdo = new PDO("mysql:host=localhost;dbname=database", "root", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
function getUser($id)
{
global $pdo;
$query = $pdo->prepare("SELECT * FROM accounts WHERE ID = ?");
$query->execute(array($id));
return $query->fetch();
}
$user = getUser(1);
echo $user['playername'];
to make it little more serious, you should use prepared statement to pass variable into query and return data from the function.
I am trying to make this query using PDO and it is returning and error.I have already verified the connection to the database.
function temperaturaMedia($data_inicio,$data_final,$ema)
{
$db = 'sensorzapp_db';
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
You are trying to execute a query on a string, you need to connect to the database, like this:
function temperaturaMedia($data_inicio,$data_final,$ema)
{
try {
$db = new PDO("mysql:host=localhost;dbname=sensorzapp_db","user","password");
} catch($ex) { die("Connection failed"); } // To not disclosure username & password when connection fails (look at the red box on http://www.php.net/manual/de/pdo.connections.php)
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();