Mysqli not importing letters - php

I am trying to make a sign up PHP for my website and I am trying to convert an old script that used mysql to mysqli. I am having a problem where that when I type any letters (abc) into any of the text fields the data is not imported into the database. If I use numbers (123) in all of the boxs it works and gets imported fine. I have tried mixing it up with some letters for the username and numbers for the password to see if only one text box was causing the problem but ANY box that have a letter in will cause the script not to work.
This is my PHP script:
<?php
$mysqli = new mysqli("localhost","root","","users_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Define username */
if(isset($_POST['username'])){
$username = $_POST['username'];
}
/* Define email */
if(isset($_POST['email'])){
$email = $_POST['email'];
}
/* Define password */
if(isset($_POST['password'])){
$password = $_POST['password'];
}
/* Define cpassword */
if(isset($_POST['cpassword'])){
$cpassword = $_POST['cpassword'];
}
if (trim($username) == ''){
echo 'No username entered.';
exit();
}
if (strlen($username) <= 5 || strlen($username) >= 30){
echo 'Username needs to be between 5 and 30 characters';
exit();
}
if (trim($email) == ''){
echo 'No email entered.';
exit();
}
if (trim($password) == ''){
echo 'Invalid password.';
exit();
}
if ($password != $cpassword){
echo 'Passwords do not match';
exit();
}
$run = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
if (mysqli_num_rows($run)>0){
echo 'Username already exists';
exit();
}
$import = "INSERT INTO users (username,email,password) VALUES ($username,$email,$password)";
if (mysqli_query($mysqli, $import)){
echo 'Registration Successful';
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
$id = $row['id'];
mkdir("../users/" . $id, 0777, true);
fopen("../users/" . $id . "/" . "New User.txt", "w") or die("Unable to create file");
}else{
echo 'Failed to import';
}
?>
I am very new to PHP and mysqli so don't be too harsh if I am doing something stupid :)

Thanks Fred -ii- putting quotes around ($username,$email,$password) worked for me and now everything works. I will also fix the other problems suggested above.

Related

PHP file doesn't execute code after connecting to a database

After I run my PHP code, hello1 is printed on the screen, but not hello2. I assume there's something wrong with my code for connect.
I can't find what's wrong with my code. Unfortunately to me my code seems correct even after going over it multiple times. How can I fix it?
BTW, I am running MAMP on a MacBook Air.
<?php
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
if (!$connect) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
echo "hello3";
}
session_start();
if (isset($_POST["Sign Up"]))
{
if (empty($_POST["Email"]) || empty($_POST["Password"]))
{
echo '<script> alert ("Both Feldsa are required)</script">';
}
else
{
$_SESSION['email'] = $_POST['Email'];
$_SESSION['password'] = $_POST['Password'];
$_SESSION['Repeatpassword'] = $_POST['Repeatpassword'];
$_SESSION['name'] = $_POST['name'];
$_SESSION['weight'] = $_POST['weight'];
$_SESSION['feet'] = $_POST['feet'];
$_SESSION['inches'] = $_POST['inches'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['goal'] = $_POST['Goal'];
// Escape all $_POST variables to protect against SQL injection
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$RepPassword = $mysqli->escape_string(password_hash($_POST['Repeatpassword'], PASSWORD_BCRYPT));
$name = $mysqli->escape_string($_POST['name']);
$Weight = $mysqli->escape_string($_POST['weight']);
$feet = $mysqli->escape_string($_POST['feet']);
$inches = $mysqli->escape_string($_POST['inches']);
$age = $mysqli->escape_string($_POST['age']);
$goal = $mysqli->escape_string($_POST['goal']);
$hash = $mysqli->escape_string(md5(rand(0, 1000)));
// Check if user with that email already exists
// We know user email exists if the rows returned are more than 0
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'") or die($mysqli->error);
if ($result->num_rows > 0) {
$_SESSION['message'] = 'User with this email already exists!';
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO User (Email_Address, Password, Full Name, Weight, Feet, Inches, Age, Goal, hash) "
. "VALUES ('$email', 'password', 'name', 'Weight', 'feet', 'inches', 'age', 'goal', 'hash')";
}
if (! $mysqli->query($sql)
{
$_SESSION['message'] = 'Registration successfully';
echo $_SESSION['message'];
header("location: loginaccount.html");
}
}
else {
$_SESSION['message'] = 'Registration failed!';
echo $_SESSION['message'];
}
}
if (isset($_POST["Login"]))
{
$email = $mysqli->escape_string($_POST['Email']);
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'");
if ($result->num_rows == 0) { //
{
$_SESSION['message'] = "User with that email doesn't exist!";
echo $_SESSION['message'];
}
else {
$user = $result->fetch_assoc();
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['email'] = $user['Email_Address'];
$_SESSION['name'] = $user['Full Name'];
$_SESSION['weight'] = $user['Weight '];
$_SESSION['feet'] = $user['Feet '];
$_SESSION['inches'] = $user['Inches '];
$_SESSION['age'] = $user['Age '];
$_SESSION['goal'] = $user['Goal '];
$_SESSION['logged_in'] = true;
$_SESSION['active'] = $user['Active'];
header("location: loginaccount.html");
}
}
mysqli_close($connect);
session_destroy();
?>
At the start of your script:
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
At line 3 here, you try and use $mysqli. That variable doesn't exist. You haven't declared it, so at that point, you are going to get a PHP runtime error when you try and reference the method of an object, which is in fact a non-existent variable.
It's actually worse than that, because you are mixing procedural mysqli with object oriented mysqli. What you really need is this, but the obvious issue is that your mysqli connection variable is named $connect!
echo "hello1";
$connect = new mysqli("localhost:8888", "Capstone", "", "capstone");
$connect->set_charset('utf8');
You can also use try/catch to find more about errors
try{
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
P.S. - in $mysqli->set_charset("utf-8"); $mysqli is not defined, use $connect here

Php mysqli_fetch_array is no working

I tried to create a register login feature in Android app. I tried to send data from my app to database by using this Php file. However, I received br/ error when I clicked register button on my app. Look like mysqli_fetch_array is not working. Anyone know how to solve this problem? Thanks!
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if($name == '' || $username == '' || $password == '' || $email == ''){
echo 'please fill all values';
}else{
require_once('dbConnect.php');
$sql = "SELECT * FROM users WHERE username='$username' OR email='$email'";
$result=mysqli_query($con,$sql);
$check = mysqli_fetch_array($result,MYSQLI_BOTH);
if(isset($check)){
echo 'username or email already exist';
}else{
$sql = "INSERT INTO users (name,username,password,email) VALUES('$name','$username','$password','$email')";
if(mysqli_query($con,$sql)){
echo 'successfully registered';
}else{
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
} else{
echo 'error';
}
dbConnect.php
<?php
define('HOST','localhost');
define('USER','username');
define('PASS','password');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
I think you should remove isset check. It'll always return true no matter what. Do count check instead.
if(count($check)){
echo 'username or email already exist';
}else{
$sql = "INSERT INTO users (name,username,password,email) VALUES('$name','$username','$password','$email')";
if(mysqli_query($con,$sql)){
echo 'successfully registered';
}else{
echo 'oops! Please try again!';
}
}

Catchable fatal error: Object of class mysqli could not be converted to string

I was trying to create a Registration form for my project but unfortunately i got this error while i could not find any error in the code!Please help me to get ride from this Issue !
my code
<?php
// this file is connected with regform.php
$firstname= $_POST['firstname'];
$lastname =$_POST['lastname'];
$email =$_POST['email'];
$password =$_POST['password'];
$confirmpassword =$_POST['confirmpassword'];
$address =$_POST['address'];
$balance =$_POST['balance'];
$password_hash = md5($password);
$bookConn = mysqli_connect("localhost", "root","", "bookstore") OR die("wrong execution");
$queryS = "SELECT Email FROM customer";
$resultSQ = mysqli_query($bookConn , $queryS);
$flag=0;
while($row=mysqli_fetch_array($resultSQ))
{
if($email == $row['Email'])
{
$flag=1;
}
}
if($flag==0)
{
if($password == $confirmpassword)
{
$query = "INSERT INTO user (firstName , LastName ,Email , Password , Address , Balance )values('".$firstname."', '".$lastname."' ,'".$email."' , '".$password_hash."', '".$address."' , '".$balance."')";
$result = mysqli_query($bookConn , $query) OR die($bookConn);
if ($result)
{
echo "successfuly Registered";
}
else {
echo "something went wrong!";
}
}
else{
echo "Passowrd does not match!";
}
}
else{
echo "Email is already existed in the Database!";
}
mysqli_close($dbc);
?>
There are two error seems in your code:-
mysqli_close($dbc). You never created $dbc in your code. It must be mysqli_close($bookConn).
You need to modified your last mysqli_query like this:-
$result = mysqli_query($bookConn , $query) OR die(mysqli_error($bookConn));
Note:- I hope by doing these changes you will get rid of your proble. Thanks.

Error in SQL syntax: Update query error

I working in my login form and 1 requirement is to have a change password. For some reason I'm always getting this error-> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' SET 'password'=SHA1('123') WHERE 'email'='mac.pader#yahoo.com'' at line 1.
<?php
$page_title = 'Change Your Password';
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('userdb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
//Start the Session
session_start();
if (isset($_POST['email']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$email = $_POST['email'];
$password = $_POST['password'];
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = $_POST['pass1'];
}
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT userid FROM `users` WHERE email='$email' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['email'] = $email;
$_SESSION['np'] = $np;
//$row = mysqli_fetch_array($result, MYSQLI_NUM);
// Make the UPDATE query:
$query = "UPDATE 'users' SET 'password'=SHA1('$np') WHERE 'email'='$email'";
$result = mysql_query($query) or die(mysql_error());
echo"$np and $email";
$count = mysql_num_rows($result);
if ($count == 1){
}else{
// Public message:
echo '<h1>System Error</h1>
<p class="error">Your password could not be changed due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
// Include the footer and quit the script (to not show the form).
//include ('includes/footer.html');
exit();
} else { // Invalid email address/password combination.
echo '<h1>Error!</h1>
<p class="error">The email address and password do not match those on file.</p>';
echo"$num";
}
}
//3.1.4 if the user is logged in Greets the user with message
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo'<h1>Thank you!</h1>
<p>Your password has been updated. You can now Log-In!</p><p><br /></p>';
}else{
echo'try again';
}
mysql_close($select_db);
exit();
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your new password.';
}
?>
You have to use backticks arround table and field names not single quotes:
UPDATE `users` SET `Password`=SHA1('$np') WHERE `email`='$email'
Also you should not use mysql_* functions because this API is depricated.

Cannot find mistake in PHP + MySQLi register page

I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']

Categories