I'm trying to get the data from table row from information via cookie.
Here's what I have so far:
$cookie_id = #$_COOKIE['id'];
$cookie_pass = #$_COOKIE['password'];
if ($_COOKIE['id']) {
if ($stmt = mysqli_prepare($mysqli, "SELECT id, password FROM `members` WHERE id=? AND password=?")) {
mysqli_stmt_bind_param($stmt, "ss", $cookie_id, $cookie_pass);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $cookie_id, $cookie_pass);
$logged = mysqli_stmt_fetch($stmt);
printf("USER ID: %s\n", $cookie_id);
// prints "1"
echo "Hello, " . $logged['username'] . "!";
}
}
And that yields: USER ID: 1 Hello, ! at the very top of the page.
What am I doing wrong? I am trying to get it so I can get the username from the table row I am trying to locate. How do I get the $logged['username'] (or any data from the row), based on the password and ID, to show up?
and adding error_reporting(E_ALL); does not show any additional errors.
You are just selecting password and id from table so when you are will fetch the data you will not get username
The general syntax is
SELECT col1,col2, .... coln FROM `members` WHERE id=? AND password=?
either you have to use * for specify the columns you want to select
your process should be something like this :
if ($stmt = mysqli_prepare($mysqli, "SELECT id, password , username FROM `members` WHERE id=? AND password=?")) {
mysqli_stmt_bind_param($stmt, "ss", $cookie_id, $cookie_pass);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $cookie_id, $cookie_pass, $username);
printf("Hello %s", $username);
}
You can refer documentation
You're trying to print the username field but the select portion of your query is only retrieving the id and password fields. Unlike mysqli_get_result() or similar functions, mysqli_stmt_fetch() only returns a boolean for success or failure, the output is passed to the variables assigned to it in the mysqli_stmt_bind_result() function. Adding $username as a third parameter to that function and adding username to the end of your select query will populate the $username variable with the user's username after the call to fetch().
To clarify, your query should be:
SELECT id, password,username FROM `members` WHERE id=? AND password=?
and the call to bind should be:
mysqli_stmt_bind_result($stmt, $cookie_id, $cookie_pass, $username);
Related
This question already has answers here:
How to search multiple columns in MySQL?
(6 answers)
Closed 2 years ago.
I have found out how to fetch for a username, however how would I do this with an email? Because, I want to add two separate error messages for an email and a username
$sql = "SELECT uid_users FROM users WHERE uid_users=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../register.php?error=usertaken&mail=".$email);
exit();
}
Use OR to check another column.
$sql = "SELECT uid_users FROM users WHERE uid_users=? OR email = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../register.php?error=usertaken&mail=".$email);
exit();
}
}
Note that this won't tell them whether it was the username or email that was already taken. If you want that, you should just do two separate queries, one that looks for a duplicate username, another that looks for a duplicate email.
Or you could change the query to SELECT uid_users, email and fetch the results of the query. Then check whether the fetched username or email matches the input, and display an appropriate error.
You can use the OR operator for this:
SELECT uid_users
FROM users
WHERE uid_users=?
OR email=?";```
If you want to check if a record exists in the database that matches both username and email then you should use WHERE uid_users=? AND email=?.
If you want to check if a a record exists in the database that matches either username or email, then use WHERE uid_users=? OR email=?.
Small note, you don't need to fetch the data if you only want to check existence of the record in DB. Simply let MySQL tell you the number of matching record. Use COUNT() for this purpose.
$stmt = $conn->prepare("SELECT COUNT(1) FROM users WHERE uid_users=? OR email=?");
$stmt->bind_param('ss', $username, $email);
$stmt->execute();
// Fetch value of COUNT(1) from DB
$resultCheck = $stmt->get_result()->fetch_row()[0];
if ($resultCheck) {
header("Location: ../register.php?".http_build_query(['error' => 'usertaken', 'mail' => $email]));
exit();
}
I am building a website where a user will enter data in a form, which will then be looked up in the database for other users that match the same criteria.
Where I am stuck is that I am trying to set up a second database that will store the search criteria they used plus some of their details. To be able to keep track of the line of data they added to the database I have included an ID to the database that will be auto incremented and would like to set this as a cookie.
In the code below, the $resultCheck is following a SELECT query that idetifies matching results.
Where should I be using setcookie in this example?
if ($resultCheck > 0) {
$sql = "INSERT INTO results (email, link, contactInfo, price) VALUES ('".$_SESSION['userEmail']."', '$link', '$contactInfo','$askPrice');";
$stmt = mysqli_stmt_init($conn);
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ssss", $email, $link, $contactInfo, $askPrice);
mysqli_stmt_execute($stmt);
}
$resultId = $row['resultId'];
setcookie("resulId", $resultId, 0, '/');
header("Location: ../results.php");
exit();
}
I have a sql statement to update confirm code and code in the database. I'm using bind param to bind the variables. It worked fine for my select and insert sql statements. However, it keeps giving me this error:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean
when I tried to execute the update query. I tried to search on every forums possible but found no answers and I hope someone could maybe spot my mistake. I'm having issues with $query1. Both code and confirmcode are varchar and not integer.
$username = $_GET['username'];
$code = $_GET['code'];
$confirmcode = "1";
$updatecode ="0";
$query=$con->prepare("SELECT username, code FROM customer_detail WHERE username ='$username'");
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query1=$con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?"); //error
$query1->bind_param('sss',$username, $updatecode, $confirmcode); //error
$query1->execute();
The problem is that MySQLi can't run multiple queries at once, because it uses ubuffered queries. You'll need to close the first statement before you can run another. Add the following line after $query->fetch();.
$query->close();
This being said, your first query isn't guarded against SQL injection, because you use the variable directly in the query. Adding proper placeholders for your query, the final code would look like this
$query = $con->prepare("SELECT username, code FROM customer_detail WHERE username =?");
$query->bind_param('s', $username);
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query->close();
$query1 = $con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?");
$query1->bind_param('sss',$username, $updatecode, $confirmcode);
$query1->execute();
$query1->close();
Try below code. Basically, you need to bind the params in the same order in which the placeholders (?) appear in the sql.
$query=$con->prepare("SELECT username, code FROM customer_detail WHERE username = ?");
$query->bind_param('s', $username);
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query1=$con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?");
$query1->bind_param('sss', $updatecode, $confirmcode, $username);
$query1->execute();
Have you tried tis?
$query1->bind_param('iis', $updatecode, $confirmcode, $username);
The problem is, I have a statement like this one below and i use it in server side of my android app
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$rows = mysqli_stmt_fetch($result);
And I want to know how many rows are back from it so I can know if there is already data in the database with the same username and email or not, but it doesn't work.
How to solve this problem? And thanks in advance.
And I want to know how many rows are back
Nope, you don't. That's a false goal.
When working with a database, you should always request the exact data you need, instead of doing some calculations on the client side.
So in your case you need the user info - so select that info. Means this very user info you can use to tell whether your query returned anything or not.
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
mysqli_stmt_execute($statement);
$result = mysqli_get_result($statement);
$user = mysqli_fetch_assoc($result);
//now you have the very $user variable to tell whether anything was found
if ($user) {
//user exists
}
All you are missing is to use the num_rows function with the resulting mysqli object:
$statement = mysqli_prepare($con,
"SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$numbRows = $result->num_rows;
//printing the result:
echo "number of rows = {$numbRows}<br>";
This question already has answers here:
PHP MYSQLI number of rows doesnt work no errors
(3 answers)
Closed 6 years ago.
I don't understand why $amountOfUsers is showing as 0?
This used to work before I moved to the bind_param function... I was only using query() instad of prepare. But this is a lot safer, I just have trouble understand why this doesn't work, and how to fix it.
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
//Counting results. 0 = Invalid, 1 = Valid
$amountOfUsers = $stmt->num_rows;
The error I am getting is: $amountOfUsers isn't counting the number of results properly.
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result (so you can get the properties, like num_rows)
$stmt->store_result();
// Get the number of rows
$amountOfRows = $stmt->num_rows;
// Bind the result to variables
$stmt->bind_result($id, $expire, $status, $db_username);
// Process the variables
while($stmt->fetch()) {
printf("%d %s %s %s\n", $id, $expire, $status, $db_username);
}
Sometimes things don't go according to plan. Checking result codes and errors available in your library is usually more efficient for troubleshooting than asking strangers, but hopefully this stranger can help... choose one of these patterns:
A:
$result = $stmt->execute();
if (!$result) { /* handle errors */ }
B:
$stmt->execute();
if ($stmt->errno != 0) { /* handle errors */ }
C (for development troubleshooting only, not code you would leave around):
$stmt->execute();
print_r($stmt->error_list);
More info here and associated pages:
http://www.php.net/manual/en/mysqli-stmt.errno.php
I would never in my life understand why php users are so inclined to the number of rows returned.
Especially if used only as a flag... if any data returned!
Why not to take the very returned data and see?
$sql ="SELECT id, expire, status, username FROM username WHERE username= ?s";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if ($row)
{
// do whatever
}
I would never understand an inclination to long and windy codes as well.
Why not to get yourself an abstraction library and get everything in one single line?
$sql = "SELECT id, expire, status, username FROM username WHERE username= ?";
if ($row = $db->getRow($sql))
{
// do whatever
}