Two queries using Mysqli - php

Problem:
Trying to run two MySQLi queries against the database but results always into a failure message.
Code (PHP):
// Checks whether submit button has been pressed
if (isset($_POST['submit']))
{
// Gets values from form fields
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
// Selects e-mail in database
$query = "SELECT * FROM userlogin WHERE email = '{$email}'";
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Checks whether e-mail exist
if (mysqli_num_rows($result) != 0)
{
// Register new user
$query = "INSERT INTO
userlogin
(username, password, email, regdate)
VALUES
('James','{$password}', '{$email}', NOW())
";
// Submit query to database
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Return success message
header('Location: index.php?notification=success');
}
else
{
// Return failure message
header('Location: index.php?notification=fail');
}
}
What am I missing? Any advice is appreciated.

Shouldn't this
mysqli_num_rows($result) != 0
be
mysqli_num_rows($result) == 0

One issue is
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
and should be
$email = mysqli_real_escape_string($link,stripslashes($_POST['email']));
$password = mysqli_real_escape_string($link,stripslashes($_POST['password']));

Related

PHP username already exists, when it doesn't

I've checked many threads about my problem, but it still won't work.
When I enter username, which doesn't exist, it will throw the username has been created yet. But, when I enter an username already registered in my db, it still register.
Here is my php/html page for register :
$error = false;
if(isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
$query = mysqli_query($sql);
if(mysql_num_rows($query)){
$error = true;
$ckname_error = "Nom d'utilisateur déjà enregistré!";
} else { unset($ckname_error); }
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,mail,password,rank) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "', 'user' )")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
header("Location: login.php");
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
You're getting unreliable results because you're mixing mysqli_ with mysql_ functions.
1. Change:
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
to:
$sql = "SELECT name FROM users WHERE name='$name'";
2. Change
$query = mysqli_query($sql);
to:
$query = mysqli_query($con,$sql);
3. Change
if(mysql_num_rows($query))
to:
if(mysqli_num_rows($query))
You missed $con, and use mysqli_num_rows not mysql_num_rows
$query = mysqli_query($con,$sql);
if(mysqli_num_rows($query)){
You're using mysqli_query($sql). You should have used 'mysqli_num_rows()' instead of mysql_num_rows().
PHP reference - mysqli_num_row
int mysql_num_rows ( resource $result ) expects resource type, whereas if you're using mysqli_query, you should have used int mysqli_num_rows ( mysqli_result $result ) - expects mysqli_results.
Let us know if it works.

PHP update table using MySQL

I have student table in my DB , and I need to create extra form in student page so he can update the details. However im getting this error ( Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\WebInterfaceLogIn\studentEdit.php on line 81)
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
include ('includes/connection.php');
// Create connection
if (isset($_POST["submit"]))
{ //Determine if a variable is set and is not NULL.
if (!empty($_POST['ID']) && !empty($_POST['user']) && !empty($_POST['surr']) && !empty($_POST['course']) && !empty($_POST['mail']) && !empty($_POST['pass']))
{ //Determine if user enters both user name and password.
$ID = $_POST['ID']; // enters user ID in database
$user = $_POST['user']; // enters user name in database
$surr = $_POST['surr']; // enters user surname in database
$course = $_POST['course']; // enters user course in database
$pass = $_POST['pass']; // enters password in database
$mail = $_POST['mail'];
// $query = mysqli_query($con,"SELECT * FROM students WHERE Student_ID='".$ID."'"); // change to update
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");
$numrows = mysqli_num_rows($query);
if ($numrows == 0)
{
$sql = "INSERT INTO students(Student_ID,Name,Surname,Course,email,password) VALUES('$ID', '$user','$surr','$course','$mail','$pass')"; // insert user name and password to database
$result = mysqli_query($con, $sql);
// Checks does user enters the details
if ($result)
{
echo '<script language="javascript">;
alert("Account Successfully Updated");
document.location.href="index.php";
</script>';
}
else
{
echo mysqli_error($con);
}
}
}
else
{
echo '<script language="javascript">
alert("All fields required")
</script>';
}
}
Can anyone can help to solve this problem?
You need pass connection object to function mysqli_query, something like this:
mysqli_query($con,"UPDATE students SET `course` = " .$_POST['course']. ", `email` = " .$_POST['mail']. " Student_ID='".$ID."'");
See more details on:
http://www.w3schools.com/php/func_mysqli_query.asp
The error is explicit enough.
add $con as a first parameter to your mysqli_query function on this line:
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

Will not return MYSQLI Results for username

I am trying to return a username when a user forgets their username. I have it validating again their email address but for some reason it just keeps saying 'Error: cannot find username'. I am using the correct mysqli syntax I hope.
if (isset($_POST['user'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$username = "";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
$errmsg = 'Error: ' . $email . ' is not a valid email address';
} else {
$query = "SELECT email FROM admin WHERE email = '$email'";
$results = mysqli_query($con, $query);
$query2 = mysqli_fetch_array($results);
if ($query2 == 0) {
$errmsg = 'Error: ' . $email . ' is not found, please try again';
}
if (!errmsg) {
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con, $getuname)) {
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: ' . $row['username'] . '</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
}
I am a noob when it comes to this but am pretty sure this is correct. if not where did i go wrong?
These are some of the errors I noticed:
You're doing if (!errmsg) but there's no such constant and you want if (!$errmsg) instead.
As Marc B pointed out, you're doing $row = mysql_fetch_array($getuname); but you want $row = mysqli_fetch_array($getuname); instead.
Also, the specific problem you're describing is probably because of the $username declaration just before the mysqli_close statement. You're resetting the value of $username there and it'd always echo out the same message regardless of the result of your database query.
$username = "";
if(condition)
{
# code ...
}
else
{
# code ...
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
That's one of the many logical mistakes in your code. Structure the if-else blocks with proper indentation and you shouldn't have this issue.
I found some mistake in your code, you can see the mistake in Mark B and Amal Murali's answer. Let me make your else block simple and more clear. you can use only 1 query instead of 2 queries.
else {
$query = mysqli_query("SELECT * FROM admin WHERE email = '$email'");
$row = mysqli_fetch_array($query);
$numrows = mysqli_num_rows($query);
if (!$errmsg){
if($numrows == 0) {
$errmsg = 'Error: '.$email.' is not found, please try again';
// or here you can add message like Cannot find username
}
else
{
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
}
Your code is a disaster. You're using ereg, which has been deprecated since the stone age. You're mixing calls to the mysql (no i) and the mysqli (with i) libraries. They are NOT interchangeable and are NOT compatible with each other.
You need to switch over to the preg functions, and standardize on a SINGLE mysql library. Since mysql is deprecated as well, use mysqli ONLY.
$row = mysql_fetch_array($getuname);
^^^---note the LACK of an i
if (!errmsg){
^^^--note the lack of a $ sign, meaning this is undefined/undeclared constant.
Change this section of code:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con,$getuname))
{
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
to:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
$uresult = mysqli_query($con, $getuname);
if (!$uresult))
{
die('Error: ' . mysqli_error($con));
}
$row = mysqli_fetch_array($uresult);
if ($row) {
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
} else {
$username = '<div class="registererror">Error: cannot find username</div>';
}
}
Your mistakes:
You were calling mysql_fetch_array instead of mysqli_fetch_array.
You were passing the SQL string to mysql_fetch_array, not the result of mysqli_query.
You weren't checking whether a row was returned, you were just setting $username unconditionally -- first to the success message, then to the failure message.

PHP Form Validator/MySQL Insert

I have written a small PHP file that gets the information that was posted to it, then checks to make sure it is no empty. If it isn't empty, it checks to make sure the username doesn't already exist. If it does, it redirects. If not, it adds the information to the MySQL database. I don't know what the problem is, but when attempting to navigate to it after pressing the submit button on the form, the browser displays an error saying that the page cannot be displayed. Here is the code.
<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['pass'];
$con = mysql_connect("localhost","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("zach_blogin", $con);
$query="SELECT username FROM members WHERE username=$username";
if (mysql_num_rows($username) > 0 ) {
header("Location: register.php?invalid");
} else {
$sql=("INSERT INTO members (username, password, FirstName, LastName, Email)
VALUES ($username, $password, $firstname, $lastname, $email)");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else {
header("Location: register.php?required");
}
?>
You are not executing the query:
$query="SELECT username FROM members WHERE username=$username";
//You need to execute the query here before you get num of rows.
if (mysql_num_rows($username) > 0 ) // also mysql_num_query takes an object.
Something like:
$query="SELECT username FROM members WHERE username=$username";
if(($result = mysql_query($query)) !== false) {
if (mysql_num_rows($result) > 0 ) {
.....
}
}
Change this
if (mysql_num_rows($username) > 0 ) {
to
if (mysql_num_rows(mysql_query($query)) > 0 ) {

Categories