i just started learning PDO...
function authenticate($username,$password)
{
$result=$this->con->query("select * from user where UserName='".$username."' AND Password='".$password."'");
var_dump($result->rowCount()); //return null
if($result)
echo "hey going great";
else
echo "Hey are you gone mad?";
}
i am calling above function with username and password... but it's returning hey going great part every time if i will pass wrong username and password also...
i tried with $result->rowCount() but it's also returning null value...
Can you suggest me what i am doing wrong here?
You are doing almost everything wrong.
First and foremost, the only reason for using PDO is using placeholders in the query.
You shouldn't also check the query result right in the function. So, make it
function authenticate($username,$password)
{
$sql = "SELECT * FROM user WHERE UserName=? AND Password=?";
$stm = $this->con->prepare($sql);
$stm->execute([$username,$password]);
return $stm->fetch();
}
and then call
if($userdata = $user->authenticate($username,$password))
echo "hey going great";
else
echo "Hey are you gone mad?";
Assuming $this->con is an instance of PDO:
PDO->query() only returns false on failure.
$result will be an instance of PDOStatement, which always evaluates to true
PDOStatement->rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Edit: By the way, your application would be more safe, if you use PDO->prepare() (& bound parameters) instead of PDO->query().
if($result)
This will always check for if the variable has any info. When ever you run a query and store in this var , it will store number of rows returned . Even if it is wrong , it will return a neg value which sets the variable.
Basically your if is just checking if the variable exists , it does exist in both cases.
if($result->rowCount()>0){
echo "hey going great";
}else{
echo "Hey are you gone mad?";
}
you can try it as:
$result=$this->con->query("select * from user where UserName='".$username."' AND Password='".$password."'");
var_dump($result->rowCount()); //return null
$num_row=$result->rowCount();
if($num_row > 0)
echo "hey going great";
else
echo "Hey are you gone mad?";
Related
I am trying to determine whether an email is aready in my database or not. For this purpose I write this piece of code:
$query_checkmail = "SELECT COUNT(*) FROM user WHERE email = ?;";
if($stmt = mysqli_prepare($connection, $query_checkmail))
{
mysqli_stmt_bind_param($stmt, "s", $_POST["email"]);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
echo "<pre>";
var_dump($result, mysqli_fetch_all($result));
echo "</pre>";
Since I expect the query to return 0 because the email should not be in the database, the output is this (from var_dump):
bool(true)
NULL
I do not understand why I do not get a mysqli result object with the value 0 but instead the boolean value true which always triggers a PHP Warning in the logs if I want to check it.
I had a normal SELECT id FROM user WHERE email = ?;"; before and got the same result. I thought with COUNT I could prevent this but my attempt has obviously failed.
I also found this Stackoverflow Link but unfortunatly it did not help my to solve my problem of getting to know whether the value already exists or not.
Any help is highly appreciated. If this information is not enough I will provide the missing bits immediatly.
The count itself doesn't return a boolean true or false, you're checking against a variable assigned from mysqli_stmt_execute(), which returns a boolean. This has nothing to do with the results of the query. If you'll read the documentation on this function, specifically the return values of mysqli_stmt_execute(), you'll see that they are either true or false, so there is no surprise that a var_dump() of that would return a boolean.
If you want the actual count, you have to use mysqli_stmt_bind_result() and mysqli_stmt_fetch() to get the results of the count. This would produce the correct results. The manuals of this would show examples of that if you are unsure how to use these functions.
http://php.net/manual/en/mysqli-stmt.execute.php
http://php.net/manual/en/mysqli-stmt.bind-result.php
As for the NULL, it's because you're passing a boolean into the mysqli_fetch_all() function, which expects a mysqli_result, while you're giving it a boolean from the above-mentioned reasons.
mysqli_stmt_execute returns true or false, you should use mysqli_stmt_get_result after the excute to retrieve the data
i copied sample code from PHP.NET
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
foreach ($row as $r)
{
print "$r ";
}
print "\n";
}
I suggest You to use PDO instead of mysqli. First make a connection, and then:
$stm = $pdo->prepare("select count(*) from user where email = :email");
$stm->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
if ($stm->execute()) {
$c = $stm->fetchColumn();
echo $c;
}
You can use MeekroDB, is the perfect php-mysql library. For example, with this code line you get similar result:
$user = DB::query("SELECT UserId FROM user WHERE email = %s",$email);
$count = DB::count();
As you can see, the code is cleaner and easy to write. Meekro is free and opensource: http://meekro.com/quickstart.php
I have the following code in my CRUD class
//function to execute prepared statement query
//$sql = select , insert, update and or delete query => insert into table(col,col,col,...col) values(?,?,?,...?);
//$dataTypes = "ssidb", it could be any char in s=>string, i=>integer, d=>double and b=>blob data
//$param = $val1,$val2,$val3,....$valn, this is an option coma separated values to bind with query
public function dbQuery($sql,$dataTypes="",$param=""){
try{
$this->connect();
$stmt = $this->con->stmt_init();
$stmt = $this->con->prepare($sql);
$stmt->bind_param($dataTypes, $param);
if($stmt->execute() === true){
return true;
}
else{
return false;
}
}catch(Exception $e){
$this->errorMsg = $e->getMessage();
}
$this->closeConnection();
}
I am calling this method from my index page like this:
if(isset($_POST['btnSearch'])){
//search for some record with primary key
$sno = intval($_POST['sno']);
$sql = "SELECT sno,std_name,email,roll_number FROM table_1 WHERE sno = ?";
$dTypes = "i";
$params = $sno;
if($db->dbQuery($sql,$dTypes,$params)){
echo('Record exists');
}
else{
echo('Record did not found'.$db->errorMsg);
}
}//search for record
//inserting values to table_1 table
This always return true either there is any record exists or not?
Whats going wrong with this code?
There are many flaws in your code, and it will never work as intended, even after fixing this particular problem.
Before starting with a class, you need to practice heavily with raw API functions, and learn how to use them by heart. Otherwise your class will be just a straw house that will crumble from a softest touch.
Now to your problem.
To solve it, you need to understand one very important mathematical conception, that reads "empty result is not an error". 10 - 5 - 5 = 0 doesn't mean there is an error in your calculations! It merely means that the result is zero.
Exacly the same is here. When a database returns no rows, it doesn't mean there is an error. It just meams that there is zero (no) data to return.
The opposite is true as well: if there is no error, it doesn't mean that there are rows found.
To see whether any row were returned or not, you need to fetch this very row.
Therefore, instead of checking execute() result, just fetch your row into a variable and then check whether it contains anything.
Would someone please me with the code below, I am inexperienced in this area and my class in SQL was "A long time ago in a galaxy far, far away..." I know the connection string works because I have used it in other functions with this app. I have even used the code below for retrieving *rows from another table in another function, for the most part, except that I didn't use the WHERE clause.
First, I am able to store IP addresses in the table using a function and it is working well. Now I want to check to see if a given one exist in this table. Partial code is given below.
What seems to always return is 0 rows. I have put in test data into the table and hard-coded the $ipA, but I still get 0 rows return. Please help if possible and thanks for the effort spent.
function checkDB($ipA) {
require_once('connection.inc.php');
$resultAns = "";
//create db connection
$conn = dbConnect();
//init prepared stmt
$stmt = $conn->stmt_init();
//Set sql query for ipAddress search
//prepare the SQL query
$sql = 'SELECT * FROM ipAddress WHERE ipA = ?';
//submit the query and capture the result
if ($stmt->prepare($sql)) {
$stmt->bind_param('s', $ipA);
$stmt = $stmt->execute();
//if qry triggers error affeted_rows value becomes -1 &
//php treats -1 as true; so test for greater than 0
$numRows = $stmt->num_rows; //not to sure about the syntax here
}
// I want to know if the query brought back something or not, I don't what
// to know exactly what, only that it found a match or did not find a match.
// echos are for testing purposes to show me where I am landing.
if ($numRows == 0) {
echo '<script type="text/javascript">window.alert("numRows = 0")</script>';
$resultAns = 0;
} elseif ($numRows == 1) {
echo '<script type="text/javascript">window.alert("numRows = 1")</script>';
$resultAns = 1;
}
return $resultAns;
}
Try storing the result after you execute
$stmt->store_result();
Use $stmt->store_result(); before you call num_rows.
While the others caught one reason that $numRows would never receive a value other than 0, the other piece of code that was flawed and caused problems was...
$stmt = $stmt->execute(); which should have been just $stmt->execute();
I must have mixed it up with other code I wrote from somewhere else.
Thanks for the answers, they did help.
I want to show the variable "points" which belongs to a certain username,.
This is a part of my login2.php file:
if(isset($_SESSION['username'])){
$username=$_SESSION['username'];
$points = $mysqli->query("SELECT points FROM account_information WHERE username = '".$username."'");
}
I dont know how to show the points now. I know that the outcome of $points is not the amount of points that belongs to a username. I actually want to know how to do this and what the outcome is of the $points. How can I show the actual result of the query I am running?(which would be the amount of points stored in my database So of course if you would run this query in mysql then the outcome will be :"Amount of points", but in this situation I dont know how to show the amount of points actually.
while ($row = mysqli_fetch_assoc($points)) {
echo $row['points'];
}
Just put the results into an array called $row then access the parts of the array with $row['points'].
The "points" value is in, after executing AND FETCHING the sql/results.
Fetch row
http://www.php.net/manual/de/mysqli-result.fetch-row.php
$sql_result = $mysqli->query("SELECT points FROM account_information WHERE username = '".$username."'");
while ($data_row = mysqli_fetch_assoc($points)) {
print 'Your score is: '.$data_row['points'];
}
OP already has accepted an answer but they both arent good imo. NDM said it, take a look into the docs it's all well written there.
I think it's also very bad practice to mix object and procedural style.
Also, the other answers don't care about security. Use prepared statements and reselect the username, because mysqli validates your $_SESSION['username'] in this case.
Take a look into this one:
<?php
// Init the database connection
$db = new mysqli("example.com", "user", "password", "database");
// Look for errors or throw an exception
if ($db->connect_errno) {
throw new Exception($db->connect_error, $db->connect_errno);
}
// Init prepared statement
$prep = $db->stmt_init();
// Prepared statement
$prep = $db->prepare("SELECT username, points FROM account_information WHERE username = ? AND username IS NOT NULL AND username != ''");
// See if statement is ok
if (!$prep) {
throw new Exception($db->error);
}
// Put your variables into the query
$prep->bind_param('s', $_SESSION['username']);
// Fire the query!
$prep->execute();
// This is magic, it's awesome.. try it :-))
$prep->bind_result($username, $points);
// Get the results easily
while ($prep->fetch()) {
echo "{$username} has {$points}<br>", PHP_EOL;
}
// This is like in our house, when we leave it, we close the door
$prep->close();
$db->close();
Update:
Answering your comment, this style is better because objects are better in general than procedural functions. Better to program, better to read, easier to understand (object abstract from real life objects).
bind_param validates your input. Imagine me putting in ;DROP TABLE account_information;-- into my username session. This is SQL Injection - the only safe way to prevent them is to prepare statements. Or Imagine having more than one database connection. Every mysqli object represents a different connection. This is not as clear as with procedural style. Also, error reporting using Exceptions is way more flexible because they can be catched and thrown.
If you want to know more about their returns, just read the manual: http://php.net/mysqli_query
mysqli_query / mysqli::query return values:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
So I have written a script to insert an email address in a table but I want to check if the address already exists. So I begin with a prepared statement:
$statement = $db->prepare("SELECT * FROM `signups` WHERE `signups_email`= ? ");
$statement->bind_param('s',$email);
$statement->execute();
if($statement->num_rows < 1){
$statement->close(); //Free up the SQL result
//do the inserting code
} else {
echo "Email already exists";
}
Trouble is, ($statement->num_rows < 1) seems to always return true, even when I know there is an email in the database. I.e. it doesn't figure out that the address is already in the database.
My connection etc is fine as the //do the inserting code bit works fine.
Take a look at the documentation for mysqli_num_rows.
Returns the number of rows in the result set. The use of
mysqli_stmt_num_rows() depends on whether or not you used
mysqli_stmt_store_result() to buffer the entire result set in the
statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be
called immediately.
It looks like you need to call store_result() before you can check the number of rows.
Your statement fails if the email already exists in the DB. the if() should be
if ($statement->num_rows == 0) {
... email does not exist, insert it
} else {
... at least one record with that email exists
}