having an issue with select query [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a query that im certain is correct but alas it is not. and that being said i am at a loss as to what could be causing the issue. here is my php script.
$con = mysqli_connect($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);
if(!$con){
echo "Connection Error...".mysqli_connect_error();
}
else
{
echo "Database connection Success...";
}
$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];
$sql_query = "SELECT name from user_info where user_name like '$user_name'
and user_pass like '$user_pass'";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row ["name"];
echo "Hello welcome".$name;
}
else {
echo "No user found";
}
?>

You haven't hadded quotes! Remember $query is a string!
$con = mysqli_connect($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);
if(!$con) {
echo "Connection Error...".mysqli_connect_error();
} else {
echo "Database connection Success...";
}
$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];
$sql_query = "SELECT name from user_info WHERE user_name like '$user_name'
and user_pass like '$user_pass'";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
$name = $row ["name"];
echo "Hello welcome".$name;
} else {
echo "No user found";
}

You forgot to wrap your query string in quotes.
You are writing query in your PHP variable so it must be wrapped in quotes.
$sql_query = "SELECT name from user_info where user_name like '{$user_name}' and user_pass like '{$user_pass'}";

What kind of error are you experiencing?
Your query should be a string, which means you'll need to surround it with quotes when assigning it:
$sql_query = "SELECT name from user_info where user_name like '" . $user_name
. "' and user_pass like '" . $user_pass . "'";
you can also use this syntax:
$sql_query = "SELECT name from user_info where user_name like '{$user_name}' and user_pass like '{$user_pass}'";
This will, however leave you open to SQL Injection Attacks.
See this part of the PHP documentation for more.

Related

im trying to make a "user taken" validation in this php code and it gives me this error: [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
this is the code that i used:
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "1234";
$dbname = "admin";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
if (mysqli_num_rows($dbunames) > 0 ) { //check if there is already an entry
for that username
echo "Already taken";
}
else{
$sql = "INSERT INTO entity (username, password)
values ('$username','$password')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>
and this is the error(in the web):
Warning: mysqli_query() expects at least 2 parameters, 1 given in
C:\xampp\htdocs\form\connect.php on line 15
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null
given in C:\xampp\htdocs\form\connect.php on line 19
New record is inserted sucessfully
i know "the record is inserted sucessfully" but the username is already taken validation is not working.
i'm not good at php so i would be pleased if you tell me how to fix this code simply.
please help me!!!
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
needs to use the $conn variable like so:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
You need to add the $conn as the first parameter in your query. Because your query is not being executed correctly the mysql_num_rows() is not working either.
Change
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
To
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
Additionally, your query as it is written now is not safe against sql injection. You should take 30 mins to read up on how to use parameterized queries. It's not bad at all, learn it now so you can make sure all your queries going forward are coded correctly. It's just the right thing to do.
Here is a good link to read that will explain parameterized queries using mysqli. Good SQL Practices
Here is an example of how to properly code your query that you have above.
$stmt = $conn->prepare("SELECT * FROM entity WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
echo "That username is already taken.";
}
$stmt->close();
You forgot to add $conn variable at the // Create connection section so it should be:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
Also Always store your passwords as Hash!!
As i said in my comment:
mysqli_query function needs two parameters to be passed.
Change this:
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
to this one:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");

Auto Login after Registeration PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem in auto login to my-account page after registration. Please help, here is my code. I am trying to login user without any email confirmation.
<?php
#ob_start();session_start();
if($_SESSION['LOGIN_ID'] > 0)
header("location:myaccount.php");
$invalidcaptcha = 0;
if($_POST['register_submit'])
{
$ip = getIP();
$emailid = $_POST['emailid'];
$pwd = $_POST['pwd'];
$confirm = '1';
$blocked = '0';
$ccode = base64_encode($email);
$ures = mysql_query("select id from user where emailid='".mysql_real_escape_string($_POST['emailid'])."'");
if(mysql_num_rows($ures) > 0 )
{
header("location:login.php?emailexist=1");
}
else if($_POST['security_code']==$_SESSION['freecap_word_hash'])
{
mysql_query("insert into user set emailid='".mysql_real_escape_string($emailid)."',pwd='".md5($pwd)."',blocked='".$blocked."',confirm='".$confirm."',ccode='".$ccode."',reg_date=now(),reg_ip='".$ip."'");
$i_id = mysql_insert_id();
$res=mysql_query("SELECT id, emailid, pwd FROM users WHERE emailid='$emailid'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
$_SESSION['LOGIN_ID'] = $row['userId'];
header("Location: myaccount.php");
}
}
?>
You are using userid here
$_SESSION['LOGIN_ID'] = $row['userId'];
And not using userId column in SELECT QUERY.
Other than to this issue, $i_id is equal to $row["userId"] than no need to use second SELECT QUERY.
In your case you just need to add userId column in this query:
SELECT id, emailid, pwd, userId FROM
But this query is extra as I mentioned.
This is another special point, stop using mysql_* its deprecated and closed in PHP 7, you can use mysqli_* or PDO.
It's better to use prepared statement, this will save your code with SQL Injection.

error in your SQL syntax; [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
hi i am getting this error though i tried to change the new to i am stil getting this problem can anyone tell me what should i do. I have completely changed the page also database but still same error.
error>
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''calendar_admin' WHERE teacher_id='ipcst123' and password='a141c47927929bc2d1fb6'
at line 1
my code >
<?php
$username=$_POST['teacherId'];
$password=$_POST['password'];
$password=md5($password);
try {
$bdd = new PDO('mysql:host=localhost;dbname=XXX', 'XXX', 'XXX');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$query ="SELECT * FROM 'calendar_admin' WHERE teacher_id="."'".$username."' and password="."'".$password."' ";
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
$res = $resultat->fetchAll(PDO::FETCH_ASSOC);
foreach($res as $result){
$pass=md5($password);
$user=$result["teacher_id"];
if ($pass==$result["password"]&& $username == $user ){
echo "login Success";
session_start();
$_SESSION['teacher_id'] = $username;
header('Location:/addEvents.php');
}else{
header('Location:/login.php');
//echo "Incorrect Password";
}
}
You should use backticks instead of single quotes :
$query ="SELECT * FROM `calendar_admin` WHERE teacher_id='".$username."' and `password`='".$password."' ";
or just remove them
$query ="SELECT * FROM calendar_admin WHERE teacher_id='".$username."' and `password`='".$password."' ";
And since you use PDO, you should bind parameters, but not concatenate them into the query:
$query ="SELECT * FROM calendar_admin WHERE teacher_id= :teacher and `password`= :password ";
$sth = $bdd->prepare($query);
$sth->bindParam(':teacher',$username);
$sth->bindParam(':password',$password);
$sth->execute();
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
Around column and table names has to be backticks, not single quotes. O rnothing if the names aren't from reserved words (or spaces, or hyphens, or anything else that MySQL will scream about, #Fred -ii- in comments below):
`calendar_admin`
The full query:
$query ="SELECT *
FROM `calendar_admin`
WHERE teacher_id = '" . $username . "' AND
password = '" . $password . "'";
Don't forget to escape data from user inputs.
$query = "
SELECT *
FROM calendar_admin
WHERE teacher_id = '$username'
AND password = '$password';
";
Next, take a look at prepared statements

Could not execute SELECT Login_Name FROM memberdirectory WHERE Login_Name = saviobosco (1054)Unknown column 'saviobosco' in 'where clause' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
$username = stripslashes($username);
// check if usernames exists
$sql = "SELECT Login_Name FROM memberdirectory WHERE Login_Name = $username";
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_num_rows($result);
// if yes, fetch the encrypted password
You are missing quotes around the string value:
$sql = "SELECT Login_Name FROM memberdirectory WHERE Login_Name = '$username'";
If you are using mysqli, why limit yourself to manually sanitizing your inputs? MysqlI has prepared statements to handle and format your query correctly.
$Conn = new mysqli("host","user","pass","database");
$Query = $Conn->prepare("SELECT Login_Name FROM memberdirectory WHERE Login_name=?");
$Query->bind_param('s',$username);
$Query->execute();
$Query->fetch();
$Row_Number = $Query->num_rows;
$Query->close(); // close the connection. Always a benefit and can save you complications later down the line
Then validate:
if ($Row_Number > 0){
} // Example only.
$username = stripslashes($username);
$sql = "SELECT Login_Name FROM memberdirectory WHERE Login_Name =".$username;
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_num_rows($result);

MySQL table does not update [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is my code
I have 2 table
booking // create to keep the booking from member
userinfo //keep username of member
<?php
$ta = $_POST['table'];
$day=$_POST['date'];
$usern = $_SESSION['username'];
$con = mysql_connect("localhost","root","password") or die ("can't connect to host");
mysql_select_db("register",$con) or die("can't connect to database");
$sql = "select * from userinfo where username = '$usern' ";
$rs = mysql_query($sql);
$row = mysql_num_rows($rs);
if($row == 0)
{ mysql_query("insert into booking(username) values '".$usern. "' ");
mysql_db_query("register");
} mysql_close();
?>
i don't know why it doesn't update.
You're missing your parenthesis in your INSERT statement:
"insert into booking(username) values '".$usern. "' "
should be
"insert into booking(username) values ('".$usern. "') "
First things first: mysql is becoming unsupported. Use Mysqli instead. It's not much different...
Then, the issue you have is to leave out the "_db". It's just mysql_query(your request). Plus, the second statement doesn't need to exist.
Need error handling? Include (before ;) "or die (mysql_error())

Categories