I've gone through quite a number of stackoverflow threads and I simply can't get it right to retrieve the results after preparing a query. I've tried a number of different solutions and none seem to be able to fetch the associative array after I execute the query
$mysqli = new MySQLi('localhost', 'root', '', 'prac2');
$query = $mysqli-> prepare("SELECT * FROM `user` WHERE username=? and password=?");
$query-> bind_param('ii', $username, $password);
if($query-> execute()) {
$query->store_result();
if ($query -> num_rows > 0) {
$result = $mysqli->query($query);
$r = $result -> fetch_array(MYSQLI_ASSOC)['userid'];
$_SESSION['userid'] = $r;
}
}
I've established that sometimes its a case of result containing a boolean for success but I'm still not certain what exactly I'm doing wrong.
UPDATED:
Okay the bind_param works now, but the fetch_assoc keeps giving me the error "Call to a member function fetch_assoc() on a non-object", I even test the result to ensure that it returns true.
$mysqli = new MySQLi('localhost', 'root', '', 'prac2');
$query = $mysqli->prepare("SELECT * FROM user WHERE username=? and password=?");
echo $mysqli->error;
$query-> bind_param('ss', $username, $password);
if($query->execute()) {
$result = $query -> store_result();
if($result) {
while($row = $result -> fetch_assoc()){
echo $row['userid'];
$_SESSION['userid'] = $row['userid'];
}
}
}
Usernames and password are strings and it should be 's' denoting that corresponding variable has type string. I don't see how usernames and passwords are integers. Bind Param Types
$query-> bind_param('ss', $username, $password);
Inside bind_param for string you should use s. I mean try ss instead of ii.
Related
I can't seem to work out how to retrieve number of rows from the database using my query, whenever I run the query It just returns zero even though it's in my database
$username = $_POST['username'];
$hash = password_verify($password, $passwordcheck);
if($stmt = $conn -> prepare("SELECT username, email, password FROM users WHERE (username = ? OR email = ?) AND password = ?"))
{
$stmt -> bind_param("sss", $username, $username, $hash);
$stmt -> execute();
$stmt -> bind_result($checkedUsername, $checkedEmail, $checkedPassword);
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
$stmt -> close();
}
echo '# rows: '.$numberofrows;
Can anyone give me any hints? Can't see to wrap my head around it, thanks.
Btw, the $hash has already been queried prior to this statement.
Posting this as a community wiki:
add $stmt->store_result(); after your execute()
As I assume you have used password_hash() on the password you store in the database. Then you should not be using it in a search criteria. Re-hashing the same string will not generate the same hash using password_hash() as it will use a different SALT each time its run Thats why its the recommended hashing tool.
So you need to do something like this
$username = $_POST['username'];
$stmt = $conn->prepare("SELECT username, email, password
FROM users WHERE (username = ? OR email = ?)")
if($stmt) {
$stmt->bind_param("ss", $username, $username);
$stmt->execute();
// As per #fred-ii- comment
$stmt->store_result();
$stmt->bind_result($checkedUsername, $checkedEmail, $checkedPassword);
$stmt->fetch();
echo '# rows: ' . $stmt->num_rows;
if ( password_verify($_POST['password'], $checkedPassword) ) {
// password is correct
} else {
// password is NOT correct
}
$stmt -> close();
}
I keep getting the same error message...
Fatal error: Call to a member function fetch() on a non-object
I've tried:
- removing quotes from ':user' and ':pass'
- changing fetch() to fetchAll()
- using PDO::FETCH_ASSOC
I can't seem to find a question that solves this, they all are solid SQL statements, there's no variables inside them.
$q = $dbh->prepare("SELECT * FROM users WHERE username= ':user' AND password= ':pass' ");
$q -> bindParam(':user', $username);
$q -> bindParam(':pass', $password);
$result = $q -> execute();
$numrows = count($result);
echo $numrows;
if($numrows == 1){
while($row = $result->fetch(PDO::FETCH_OBJ)){
$row["id"] = $_SESSION["id"];
$row["username"] = $_SESSION["username"];
$row["password"] = $_SESSION["password"];
$row["email"] = $_SESSION["email"];
}
} else {
header("location: index.php?p=5");
}
Fetch should be used on the PDOstatement object.
According to the PDO manual:
PDOStatement::fetch — Fetches the next row from a result set
The fetch function is a member function of the PDOStatement object.
Example from the manual:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute(); //no need in another variable, like: $r = $sth->
/* Exercise PDOStatement::fetch styles */
$result = $sth->fetch(PDO::FETCH_ASSOC); //$sth, not "$r"
Another note:
Regarding your usage of execute, according to the manual it returns a boolean value (true/false) and not an array of values.
I believe you've used mySQL so the "migration" to PDO is a bit strange for you, look at the manual and follow some tutorials.
Remove quote from user and pass
$q = $dbh->prepare(" SELECT * FROM users WHERE username= :user AND password= :pass");
I'm trying to count the rows returned from the database. When i run this code this will give me return of 1 row which contains a username and password but when i try to count the rows it allways give back zero even tho database is actually returning rows.
$row_count =$stmt -> num_rows only returns 0.
$stmt = $mysqli -> prepare
("SELECT username, password FROM members WHERE username=? AND password=?");
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> bind_result($returned_username, $returned_password);
$stmt->fetch();
$row_count = $stmt -> num_rows;
echo $row_count;
echo $returned_username;
echo "<br />";
echo $returned_password;
$stmt -> close();
$mysqli ->close();
Use $stmt->store_result(); before getting the num_rows.
More info: http://php.net/manual/en/mysqli-stmt.num-rows.php
Try this:
$stmt = $mysqli -> prepare
("SELECT username, password FROM members WHERE username=? AND password=?");
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> store_result(); //You need to store the results first
$stmt -> bind_result($returned_username, $returned_password);
$stmt->fetch();
$row_count = $stmt -> num_rows;
echo $row_count;
echo $returned_username;
echo "<br />";
echo $returned_password;
$stmt -> close();
$mysqli ->close();
trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.
I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}