Where do you have to position setcookie in php code? - php

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();
}

Related

How would I fetch for data for an email and a username? [duplicate]

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();
}

How do I store a $_SESSION value within my database

I've been trying to store the session userUid and put it in the database under id. I want it to merge the two ids from different databases.
I tried setting the userUid as a variable and putting it into the database. userUid is the id from the signup/login page and profiles is the database i'm trying to insert it into.
if(!isset($_SESSION['userUid'])){
header("location: index.php"); // Redirecting To Home Page
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'] . "<br>";
}
}
}
I expect it to out put the newly inserted $_SESSION['userUid'] as "id" from the database profiles.
A few things to note,
Your current logic will never really work, because you only execute the query when the session-value is not set
You should always exit; after a header("Location:..."); call
You should be using prepared statements and bind your values through placeholders
An insert query has no num_rows (the equivalent is affected_rows for insert/update/delete queries) or fetch_*() methods associated with them.
if (!isset($_SESSION['userUid'])) {
header("location: index.php"); // Redirecting To Home Page
exit;
}
$sql = "INSERT INTO profile (id) VALUES (?);";
$stmt = $conn2->prepare($sql);
$stmt->bind_param("s", $_SESSION['userUid']);
$stmt->execute();
echo $stmt->affected_rows." rows inserted";
$stmt->close();
In order to properly check for errors, you should enable MySQLi exception mode by adding the following line before you create your MySQLi connection. That means that you have to use a try/catch for your query statements, but in turn means that you don't have to do individual error-checking for each function-call.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You are trying to use mysqli_fetch_assoc on an insert query.
You could either just use $_SESSION['userUid'] or you can make a seperate select query to get the new row from the database.
First check the "if" condition in your code.
if(!isset($_SESSION['userUid'])):
...
else:
...
endif;
The final solution to you,
if(!isset($_SESSION['userUid'])):
header("location: index.php"); // Redirecting To Home Page
else:
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0):
while ($row = mysqli_fetch_assoc($result))
{
echo $row['id'] . "<br>";
}
endif;
endif;

PHP Checking if the email already exists in the database

I am making a website with a login system. When the user wants to sign up and enters his email, there should not exist one in the MySQL database already. I am trying to make my code through prepared statements.
When the user enters an email that already exists in the database I want it to send the user back to the same signup page with the header function with some kind of error. I tried to store the number of rows in a variable called $resultcheck and check whether or not there are columns that have the same email more than 0 (if it already exists).
Here is the code:
$query = "SELECT * FROM users WHERE Mail=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $query))
{
header("Location: ../registrering.php?error=sqlerror");
exit();
}
else
{
mysqli_stmt_bind_param($stmt, "s", $mail);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if($resultcheck > 0)
{
header("Location: ../registrering.php?error=emailtaken");
exit();
}
else {...}
When I submitted however an account with an already existing email in the database then I succesfully entered another column in the table users and have more than one column with the same email.
You are assigning $resultCheck and then testing for another variable called $resultcheck which will always be 0.
So your mistake is a typo in your variable naming.
Beside of checking with a SELECT SQL. You should set the column in mysql to unique. See https://www.w3schools.com/sql/sql_unique.asp.

MySQLi prepare statement gives blank responses

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);

PHP & SQL Insert data Into Table1 if input data exists in Table2

I've been trying to figure out how to insert data received from a form into one table only if the received data exists in another table. If the data doesn't exist it moves onto another query and checks another table for the received data.
This is what I'm trying to do:
function addNewUser($username, $password, $email, $actcode){
$time = time();
$q = "UPDATE ".TBL_RELEASE_CODES." SET code = '$actcode' WHERE code = '$actcode'";
$result = mysql_query($q, $this->connection);
if (!$result || (mysql_numrows($result)) == 0){
$q = "INSERT INTO ".TBL_RELEASE_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', '$actcode', $time)";
return mysql_query($q, $this->connection);
}
The purpose of this is that when the user submits a special code the system will run checks to see if the code belongs to a certain table.
If it finds the submitted code in a table it will run the insert query associated with the check, if not then it breaks and returns an error saying no match was found.
I'm probably using the code incorrectly as I've been scrounging information from Google searches and testing them out. With no luck yet.
This code is being run off a website using PHP 5 and MySQL.
The first query doesn't do anything -- it sets code to $actcode only in the rows where code is already $actcode. You should use a SELECT, not UPDATE:
$q = "SELECT COUNT(*) FROM ".TBL_RELEASE_CODES." WHERE code = ?";
$stmt = mysqli_prepare($this->connection, $q);
mysqli_stmt_bind_param($stmt, 's', $actcode);
mysqli_stmt_bind_result($stmt, $count);
mysqli_execute($stmt) or die "Query failed: ".mysqli_stmt_error($stmt);
mysqli_stmt_fetch($stmt);
if ($count == 1) {
// Insert into TBL_RELEASE_USERS
} else {
// Return error saying no match found
}
You should also not use the mysql_XXX functions. They're deprecated and make it hard to avoid SQL-injection attacks. My code above uses mysqli_XXX, which supports prepared statements to protect against that. It also has an OO-style API if you like, but I didn't use that above.

Categories