Mysqli undefine variable - php

Hi I am working on simple crud project with php and mysqli statement.
First everything was working good, but for instance mysqli_num_rows($result) returns more than one row which cause all errors.
this is my PHP code
<?php
if(isset($_GET["email"]) && !empty(trim($_GET["email"]))){
// Include config file
require_once 'db.php';
// Prepare a select statement
$sql = "SELECT * FROM interns WHERE email = ?";
if($stmt = mysqli_prepare($con, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["email"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$cin = $row["cin"];
$phone_number = $row["phone_number"];
$address = $row["address"];
$school = $row["school"];
$intern_duration = $row["intern_duration"];
$departement = $row["departement"];
$cv = $row["cv"];
$internship_report = $row["internship_report"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
I know it's might be a very simple error but it driving me crazy xD

mysqli_stmt_bind_param($stmt, "i", $param_id) that should be an s for a string, being for the email address. The i stands for "integer".
Your query probably returns more than one row because there are (probably) more than one row containing an integer.
You could also add a LIMIT 1 to the query which may help.

Related

Count function is not working properly for sql's result

I wrote code for sign up where I check username , if it is exists in database or not than add new user accordingly. I am new to sql->prepare statement, Problem is in count function , when checking username it works properly, but in else part when adding user it gives me following error
Uncaught TypeError: count(): Argument #1 ($value) must be of type
Countable|array, bool
Here is my adduser.php code.
<?php
include 'config.php';
//checkusername
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username);
$username = $_POST['username'];
$check->execute();
$row = $check->fetch(PDO::FETCH_ASSOC);
if(count($row)){
echo -1;
}
else{
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
$sql->bindParam(1,$name);
$sql->bindParam(2,$username);
$sql->bindParam(3,$password);
$name = $_POST['name'];
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql->execute();
echo 1;
}
?>
It doesn't make much sense to use count here, you don't need to know how many fields are in the row.
Just check if it's false or not - see php.net/manual/en/pdostatement.fetch.php which mentions that fetch() will return false when it fails (i.e. there is no row available).
This would make more sense:
if($row) {
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
//...etc...
}
else {
echo -1;
}
After executing the query with $check->execute();, you can use the built-in method to count the returned rows: $check->rowCount();.
I think the statement above returned 0 rows, so you can't do $check->fetch() and it returns false.
Example:
// Your code here...
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; // This line needs to be before the next one, because you used the variable $username before defining it
$check->bindParam(1,$username);
$check->execute();
if($check->rowCount() > 0) {
// User does exist
} else {
// User does not exist
}
Edit 2: I just realised that the answer I've given below is wrong. The thing I suggest instead is checking if there's any value by using the PDO rowCount() method, like this: if ($check->rowCount()>0)
wrong stuff below
You're assigining $username a value after binding it.
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username); //bind $username
$username = $_POST['username']; //assign value
$check->execute();
Try switching those two lines so $username is assigned a value when you're binding it.
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; //assign value
$check->bindParam(1,$username); //bind $username
$check->execute();
Edit
In case you're still having issues, try checking if there's any error in the sql statement execution.
After your $check->execute(); you can add print_r($check->errorInfo()); to see if your MySQL statement has any issues in it.

Why does the user input not append to my SQL database?

I'm developing a login/register form for my client. Right now I am working on the registration part of the form however I seem to have encountered an issue.
I am trying to append the user's input to a database if it does not currently exist. I'm developing this functionality using PHP version 7. However, the code does not seem to append the data to the database even when telling me it has done so successfully.
Here is code:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
//define variables and set values to null
$email = $code = "";
//set variable values to HTML input
$email = $_POST['email'];
$code = $_POST['code'];
//check if email exists
$stmt = $conn->prepare("SELECT userEmail FROM userDetails WHERE userEmail=?");
$stmt->bind_param("s", $prepemail);
//set parameters and execute
$prepemail = $email;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "email exists";
return false;
} else {
//$stmt->close(); removed as per #Akintunde-Rotimi's suggestion
//insert email into database
$stmt = $conn->prepare("INSERT INTO userDetails (userEmail) VALUES (?)");
$stmt->bind_param("s", $newemail);
//set parameters and execute
$newemail = $email;
$stmt->execute();
echo "New records created successfully";
}
}
?>
The code successfully connects to the database and even tells me if the user already exists. It just doesn't add the user's email to the database and I can't seem to figure out why.
I have researched methods on how to insert the data into the database using prepared statements as I have done here. I've used W3Schools as a reference but still no luck.
The code doesn't seem to have any obvious spelling errors, so have you tried to catch errors? Replace
$stmt->execute();
with
if(!$stmt->execute()) {
trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}
You can also check how many rows are affected, -1 meaning there was an error.
printf("%d Zeile eingefügt.\n", $stmt->affected_rows);
Also, enabling more errors to be shown (at least for development)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// ...

How to update MySql column from -1 to 1 after login from PHP script

Before I ask the question, I know there are issues with the SQL Injection, I am going to take care of it most likely with PDO, I am just trying to figure this out for now.
I want PHP to read the status column from MySql and if the status column reads -1 where $username = ($_POST["username"]) I want PHP to initially send them to a "change password" screen and then after its changed send an update script to MySql to update column "status" from the default -1 to 1.
If its 1 I want it to log in as normal and if its -1 I want them to be forced to change their password basically and I am having trouble locating a way to do this.
Im assuming my update query would look something like this
$query = "UPDATE login SET status= 1 WHERE user_id='".$username ."' LIMIT 1";
My php login script so far
<?php
// Include config file
require_once 'LoginConn.php';
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = 'Please enter username.';
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST['password']))){
$password_err = 'Please enter your password.';
} else{
$password = trim($_POST['password']);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT username, password FROM scorecardusers WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
/* Password is correct, so start a new session and
save the username to the session */
session_start();
$value= $sql['password'];
$_SESSION['username'] = $username;
header("location: Test.php");
} else{
// Display an error message if password is not valid
$password_err = 'The password you entered was not valid.';
}
}
} else{
// Display an error message if username doesn't exist
$username_err = 'No account found with that username.';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
UPDATED: I added this to my query and it updates correctly.
mysqli_query ($link, "UPDATE Users SET Status = '1' WHERE Status ='-1'and username ='".$username ."' LIMIT 1");
If anyone could help me understand how to pull the status area from my sql and redirect them to the change password page if the status =-1 that would be awesome.
I am just trying to figure out how to redirect to change password if Status =-1 in mysql..
SECOND UPDATE: Ive made a second query that checks the information and sends you to the change password log however I know this is not correct. I feel as if I am getting a lot closer to the answer though. The code works as far as getting me to the right screen but its not getting the correct information. I need the username to be a variable based on what the agent puts in. Again, any help here would be really appreciated.
$id_get = "SELECT Status, username FROM scorecardusers WHERE Status = '-1' and username='MyName' LIMIT 1";
if ($result=mysqli_query($link, $id_get))
{
// Fetch one and one row// check if first time log in
while ($row = mysqli_fetch_assoc($result))
{
$Status=$row["Status"];
$username=$row["MyName"];
if ($Status== "-1" && $username =="MyName");
var_dump($result);
header("location: ChangePW.php");
}
// Free result set
mysqli_free_result($result);
}
I added the update query I posted above after the following code. This has solved my problem and accurately check if the user was logged in before, if they have the website directs them to a change password, if they have logged in it send them to the website. I created a separate query to select status and username so it would not interfere with the password. I am assuming this would work with any user name considering it is completely variable as long as they never logged in before it should direct them. If there is any issues with this code id love to know, however it is working correctly for me.
$id_get = "SELECT Status, username FROM Users WHERE Status = '-1' and username = ?";
if($Check = mysqli_prepare($link, $id_get)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($Check, "s", $param2_username);
// Set parameters
$param2_username = $username;
$param_status=$status;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($Check)){
// Store result
mysqli_stmt_store_result($Check);
if(mysqli_stmt_num_rows($Check) == 1){
// Bind result variables
mysqli_stmt_bind_result($Check, $username, $param2_status);
if(mysqli_stmt_fetch($Check)){
if ($param_status== "-1" && $param2_username == '?');
header("location: ChangePassword.php");
}
}
}
}

Get the rows and display them in echo mysqli prepared

im trying to get the rows from database with mysqli prepare statments and display them in echo like <?php echo $username; ?> but don't know how to get them , wasted 4 hours no success , help would be greate
php
<?php
include("secure/functions.php");
session_start();
$stmt = $mysqli->prepare("SELECT * FROM members WHERE username = ?");
$stmt->bind_param('s', $_SESSION['username']); // Bind "$username" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) {
$stmt->bind_result($id,$username); // get variables from result.
$stmt->fetch();
}
?>
You initially used $session_start(); where it should be session_start(); no dollar sign.
Try to check existence of session_start(); at begin of your script.
And, you can check which value sets to prepared statement - before binding of parameter $_SESSION['username'], try to display this value with echo or print.

Having problems going from mysqli_query to mysqli_prepare

I'm new to PHP and made a simple php site that allows me to submit a form and delete data stored in a database. I was told it was better to use prepared statements to avoid SQL Injection.
I updated my delete and it still works, not sure if it's totally right:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN ($getid)");
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
But I can't seem to get the add to database feature to work. I tried a variety of different ways to write it, but I'm sure that I'm missing something simple. Here's the unsafe code that I originally wrote:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
//execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
exit;
}
?>
If someone could guide me in the right direction I'd be thankful. I'm new to all of this.
UPDATED: I've updated my original code and came up with this instead for delete:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN (?)");
mysqli_stmt_bind_param($delete, 's', $getid);
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
and the add feature:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
$firstName = "$_POST[firstName]";
$lastName = "$_POST[lastName]";
$email = "$_POST[email]";
$phone = "$_POST[phone]";
// assigns form data to table columns
$assign = mysqli_prepare($database,"INSERT INTO contacts(firstName,lastName,email,phone) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($assign, 'ssss', $firstName, $lastName, $email, $phone);
mysqli_stmt_execute($assign);
exit;
}
?>
A simple Prepare statement is something along the lines of
$query = $this->db->prepare("Query here WHERE something = ?") - note this example is taken from my site so you'll likely have something else instead of $this->->prepare.
The key thing is that the "= something " is denoted as a question mark.
You then bind the value of that question mark to the query
$query->bindValue(1, passed in parameter)
As a fully working example:
//function to add 1 to downloads each time a file is downloaded
public function addToDownload($filename){
$query = $this->db->prepare('UPDATE trainingMaterial SET downloads = downloads + 1 WHERE filename = ?');
$query->bindValue(1, $filename);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
Your query `$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
would be
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ?,?,?,?,?)";
$assign->bindValue(1, '$_POST[firstName]')
$assign->bindValue(2, '$_POST[lastName]')
etc etc

Categories