I know this might be a duplicate on:
php - MYSQLI_NUM_ROWS ALWAYS RETURNING 0
php - mysqli_num_rows() is always returning 0
The thing is none of them is giving me an answer for my problem.
This is an example code of my code with the same syntaxes as I used.
index.html
<html>
<head><title>GAS - Give Away System - Create User</title></head>
<body>
<script src="jquery.js"></script>
<input type="text" placeholder="Username" id="uname" /><br><br>
<p id="errors"></p>
<script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
setInterval(function(){
$("#errors").load("php/errorchecking.php?c=username&v="+document.getElementById('uname').value);
}, 500);
});
</script>
</body>
</html>
php/errorchecking.php
<?php
$con = mysqli_connect('localhost', 'root', '', 'gas');
if(isset($_GET['c']) && isset($_GET['v'])){
echo 'Current value: ', $_GET['v'], '<br>This value is set for: ', $_GET['c'], '<br><br>';
if($_GET['c']==="username"){
if($_GET['v']===null){
echo "Sorry, this username is empty! Please write a username!";
}else{
// I know this is open for SQL Injection, it's not in my worries.
$query = "SELECT `username` FROM `users` WHERE `username` ='{$_GET['v']}'";
$sql = $con->query($query);
if(mysqli_num_rows($sql) > 0){
echo "Sorry, this username is already in use! Please choose something else";
}else{
echo "Username avaible!"; //This is line 17
}
}
}
}else{
echo 'This is an invalid form!';
}
?>
Now lets say I have a username in my table called User15, and someone's input is the exact same it will display the message "Username available!" from php/errorchecking.php Line:17
Why does it do that? Since it already is a user there called User15, so what it should display is "Sorry, this username is already in use! Please choose something else"
Thanks for taking time helping me! Cecilie.
That's a wrong way of query syntax. You need to use back-ticks and not 's:
$query = "SELECT username FROM `users` WHERE 'username'='".$_GET['v']."'";
//-------------------------------------------^--------^
Change it to:
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";
Note:
`` - For columns.
'' - For values.
You have to remove '(single quotes) around your column-name from your query like below:-
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";
Note:- Instead of '(single quotes) use back-ticks. because single-quotes(') used for values and back-ticks used for column-name as well as table-name too.Thanks
Related
Can somebody help regarding to my PHP and jQuery? I try to change my password using PHP, jQuery and Ajax. I know this method is kind of weird. But I want to explore more about Ajax, jQuery with PHP. I want to UPDATE my password without showing or typing the current password. I want my textbox empty and if I input something it will change my password in my db table. Don't need to type my current password. My problem is it didn't update my password. How can I update my db password? depends who is login.
<?php
$conn = new mysqli("localhost", "root", "", "mydb");
if(isset($_POST["btnChange"])) {
$checkUser = $conn->query("SELECT * FROM tbl_user WHERE id= $_SESSION[id]");
if ($checkUser->num_rows > 0) {
$conn->query("UPDATE tbl_user SET password = '$_POST[new_password]' WHERE id= $_SESSION[id]");
echo "Update Successfully!";
}
}
?>
$(document).ready(function(){
$("#btnChange").click(function(){
$.ajax({
url:"insert.php",
method:"post",
data:{btnChange: "", new_password: $("#new_password").val(),},
success: function(data){
alert(data);
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery/jquery.js"></script>
<script src="changeapasswordjs.js"></script>
<title>Change password</title>
</head>
<body>
<h1>Change password</h1>
<form id="simpleForm">
<div>
<label for="new_password">Your new_password</label>
<input type="password" name="new_password" id="new_password" />
</div>
<br>
<div>
<button id="btnChange">Change password</button>
</div>
</form>
</body>
</html>
To access an array, the key must be in quotes like so ['key']. Also, you can wrap {} around the variable to output it inside a string.
// First query you do
$checkUser = $conn->query("SELECT * FROM tbl_user WHERE id = '{$_SESSION['id']}'");
// Second query you do
$conn->query("UPDATE tbl_user SET password = '{$_POST['new_password']}' WHERE id = '{$_SESSION['id']}'");
You're also missing the content type you're outputting and should encode your response in json:
header('Content-Type: application/json');
echo json_encode("Update Successfully!");
Furthermore, to access the super variable $_SESSION you must first use session_start() prior to accessing the variable.
Further, none question related but a key point moving on, your queries are prone to SQL injection and you should consider turning error logging on.
First of all, i think your code misses a very important statement which is the session_start() statement.
Secondly, the id session can't be called the way you are calling it in your code, you have to add quotes like this $_SESSION['id'].
You also need to add quotes in the WHERE clause so it becomes a valid statement like the following: WHERE id = '$_SESSION['id']'.
Again, you are accessing $_POST array the wrong way, you have to add the quotes like this $_POST['new_password'].
After correcting these mistakes, the final code should look like this:
<?php
session_start(); //Initializing session
$conn = new mysqli("localhost", "root", "", "mydb");
if(isset($_POST["btnChange"])) {
$checkUser = $conn->query("SELECT * FROM tbl_user WHERE id='".$_SESSION['id']."'");
if ($checkUser->num_rows > 0) {
$conn->query("UPDATE tbl_user SET password = '".$_POST["new_password"]."' WHERE id='".$_SESSION['id']."'");
echo "Update Successfully!";
}
}
?>
UPDATE
Please reproduce the code to this, it is recommended to use an else statement in case the user doesn't exist.
<?php
session_start(); //Initializing session
$conn = new mysqli("localhost", "root", "", "mydb");
if(isset($_POST["btnChange"])) {
$checkUser = $conn->query("SELECT * FROM tbl_user WHERE id='".$_SESSION['id']."'") or die(mysqli_error($conn));
if ($checkUser->num_rows > 0) {
$conn->query("UPDATE tbl_user SET password = '".$_POST['new_password']."' WHERE id='".$_SESSION['id']."'");
echo "ID: ".$_SESSION['id'];
}
else {
echo "User doesn't exist.";
echo "<br>ID: ".$_SESSION['id'];
}
}
?>
I am trying to create a simple search bar that allows the user to search using a user id to return a specific user.
I need to include SQL injection protection.
currently the page loads a blank screen but when I refresh the page I get the "No results found" response.
I have been reading a lot of posts about search bars but nothing is helping me.
here is the code:
<html>
<head>
<title></title>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="search" />
<input type="submit" value="Search" />
</form>
</body>
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysqli_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = '$safesearch'";
$Result = mysqli_query($DB,$Query);
$NumResults = mysqli_num_rows($Result);
if ($NumResults==1)
{
echo "<h1>results: ".$Result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
You should have an if(isset($_POST['submit']{ } around your code so it only fires if they search and not when the page is loaded.
If you're doing any sort of insert,select or update with sql statements that will have variables within them you should use prepared statements.
Use a prepared statement it's a lot more safe than what you're doing:
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysql_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = ?";
$stmt = $connectionVariableName->prepare($query);
$stmt->bind_param("s",$safesearch);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$num_rows = $stmt->num_rows;
$stmt->close();
if ($num_rows > 0)
{
echo "<h1>results: ".$result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
http://php.net/manual/en/mysqli.prepare.php
You should also sanitize the search variable by testing it with regex to make sure it only contains the characters you allow in the userid and not / * ^ etc
You want partial phrase search, I presume.
Then your query must look like this:
$Query = "SELECT user_id
FROM users
WHERE user_id LIKE '%$safesearch%'";
Not very familiar with php, but % symbol seem not being a special character in the language (correct me if I'm wrong), if it by chance is - escape it.
To make it case insensitive -
$safesearch = strtolower($safesearch);
$Query = "SELECT user_id
FROM users
WHERE lowercase(user_id) LIKE '%$safesearch%'";
<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.
I got the error: unknown column in field list, while I know for sure I haven't made any typos and the columns exist.
Anyone know what I'm overlooking?
<?php
//create_cat.php
include '../includes/connection.php';
$cat_name = mysql_real_escape_string($_POST['cat_name']);
$cat_description = mysql_real_escape_string($_POST['cat_description']);
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo "<form method='post' action=''>
Category name: <input type='text' name='cat_name' id='cat_name'/>
Category description: <textarea name='cat_description' id='cat_description' /></textarea>
<input type='submit' value='Add category' />
</form>";
}
else
{
//the form has been posted, so save it
$sql = 'INSERT INTO categories(cat_name, cat_description) VALUES ($cat_name, $cat_description)';
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
echo 'New category successfully added.';
}
}
?>
Try this:
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
Update:
You used ' to start a string. When doing this its not possible to use variables in the text, they will just be leaved as plain text. But when using " the variables will be evaluated.
The problem is your SQL query. You used single quotation marks, which is for a literal string. Your variables will not be parsed in. You need to use double quotation marks. Not only that, but for strings, you need to put single quotation marks around them when putting them into queries.
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
You should also try not to use mysql_* anymore. It's been depreciated (meaning it will be removed from PHP soon). Try looking at MySQLi (very similar to MySQL) or PDO instead.
<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:
If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}
That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection
You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.
This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)
As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!