i'm trying to learn PHP/MySql and create a simple "website".
I have a problem while i try to print a row from a Select. I created a Database with the table "Utenti" and i want to select an username from it.
$username='Prova';
// In my database there is a record with username "Prova"
require 'connessione_db.php';
// I connect Php to the Database in another file
mysqli_select_db ($conn, $dbname);
$checkusername= "SELECT username FROM utenti WHERE username= '$username' ";
// when i write "Where username='Prova' " there aren't problem.
$username_result=mysqli_query($conn,$checkusername);
if (mysqli_num_rows($username_result) > 0) {
while($rows=mysqli_fetch_array($username_result)) {
echo $rows['username'];
}
} else {
echo "no";
}
With actual code the result is "no", but if i write:
... where username='Prova'";
the result is "Prova".
I tried to change the code reading user's solutions without success. I tried:
" ... Where username='" .$username. "'";
or
mysqli_real_escape_string($conn,$username);
and other useless advice.
When you're adressing to your sql server you're using string so you jsut need to merge two strings so username='" .$username. "'" should work just fine. What might work is something like "...username='{$username}". You should debug this string by using error.log($checkusername) what's wrong with your string. Also what version of php you currently using? Best stable version are 5.6 or 7.3.4 although 7+ versions isn't popular.
Related
I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>
I am creating a sign up page.
My code was working perfectly before on an intranet, but now, 5 years later I must use MySQL i.
What happens is I connect to the database using external PHP file, dblogin.php
<?php
$connection = mysqli_connect('mywebhost','username','password','db');
?>
That bit works fine, as the login system works using this.
Then comes my registration system.
It has been a while since I coded in PHP, mostly working using Wordpress now.
<?php
include 'dblogin.php';
if(isset($_GET['i'])){
if($_GET['i'] == '1'){ //if we want to insert a new user
$tblName="tblUsers";
//Form Values into store
$FirstName=$_POST['firstnamecreate'];
$Surname=$_POST['Surnamecreate'];
$Username=$_POST['UsernameCreate'];
$UserType="stu"; //never mind this, it just seperates admins from standard users
$Email=$_POST['EmailCreate'];
$Password=$_POST['PasswordCreate'];
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
if($UserResults[0] == 1){
$CreatedStatus = "$Username already exists in the user database. Please choose a different Username.";
}else{
$sql="INSERT INTO $tblName(UserName, Password, UserType, FirstName, Surname, EmailAddress)VALUES('$Username', '$Password', '$UserType', '$FirstName', '$Surname', '$Email')";
$result=mysqli_query($connection,$sql);
if($result){
$CreatedStatus = "$FirstName, you have registered successfully. Click " . "<a href=Login.php>". "HERE". "</a>" . " to login. " . "<br />"."Please note: Hacking of this site is not permitted.";
}
else {
$CreatedStatus = "Unfortunately $Username was not created successfully. Please check your entry or check whether the user already exists.";
}
}
}
}
?>
The problem i am getting is around the
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
part.
I have tried all sorts. With the current format, it results in:
Warning: mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26
removing $connection results in it expecting 2 parameters and removing i says depricated.
Any help much appriciated. It has been a while since I last used php so sorry if the code is untidy. The select COUNT (*) checks if there is another user with the same username, if there isnt it will submit form values to the DB
This error is coming from the extremely simple fact that you are sending an empty query to mysqli. The query is empty. It's but an empty string. Nothing.
So just check your variables.
The second parameter to mysqli_query() should be a PHP string contains a legitimate SQL query. Anything else will cause an error.
i know maybe this post will be marked soon as duplicate, because there are a lot of questions answered but i dont know why it is not working for me (as always) here is this part of code:
$conn->set_charset("utf8");
$query = mysqli_query($conn, "SELECT * FROM User WHERE Username='".$username."'");
if(mysqli_num_rows($query) > 0){
echo "exists";
}else{
if (!mysqli_query($conn,$query))
{
echo "free";
}
}
}
Problem is : I'm always getting "Free"
thanks
-Nick
Try fetching the values and then using the php count() function on the query result. If count is greater than 0 echo taken else free
Why do you use a password in this query if you only want to check is a username is available? Did you also dumped the $numrows var to see which data it contains?
I would use something like
SELECT id FROM users WHERE username='username' LIMIT 1
You want to know if a username is available, so stop looking after you found 1 (LIMIT 1). If I ask you to find me 1 spoon,
As many others suggest, stop using the deprecated mysql_* functions. Try reading the tutorials on https://phpdelusions.net/pdo (much more can be found via Google)
When using PDO I think you can use the following code. Forgive me if it contains errors, it has been ages since I just PDO directly:
<?php
$checkUser = $pdoConnection->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
$checkUser->execute([$username]);
if ( $checkUser->rowCount() == 1 )
{
return 'Username exists';
}
# Username is available, so continue with the rest of your code
Small tip from me, based on experience, which has nothing to do with your question; never use capitals in your database. It could lead to unnecessary problems.
Your Username and Password are in quotes, so it is taking them literally.
Try this:
$query = mysql_query("SELECT * FROM User WHERE Username='" . $usernameG . "' and Password='" . $passwordG ."'");//quotes
I've been searching for a couple of hours trying to figure this out:
person types his username in a text field and hits submit, then php checks if the username is in the database(in the table username). What method do i use? or what statement. Because this is really confusing me.
my database is named arcforum table is named afusers the rows are filled with usernames and what not.
Visual reference:
I tried using:
SELECT username FROM afusers WHERE username LIKE 'DarkEyeDragon';
But this returns nothing.
PS: I'm not asking for the completely filled in code(although always welcome). Just a method I can use to do this. Or a simular question.
Thanks in advance.
EDIT: http://i.imgur.com/4V0Cay1.png Proof table/database is not empty
Code:
include_once 'psl-config.php';
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
header("Location: ../error.php?err=Unable to connect to MySQL");
exit();
}
The next part just prints out every row in the table. Just to make sure everything is working as intended.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "| Name: " . $row["username"]. "<br>email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
exit();
after that i'm not entirly sure how I would utilise the code to check if the words are the same.
$mysqli->query('select * from afusers where username = someusername')
You can verify the row quantity with $mysqli->num_rows
And then you can fetch your data like this:
$user = mysqli_fetch_object($mysqli)
That will give you the desired user if the username is unique.
Of course you could use a variable for the username like:
$mysqli->query('select * from afusers where username ="' . $username . '"')
Being quite new with PHP, I cannot find any solution why this does not work. The query is OK and the resource is returned. But I dunno why fetch_assoc does not print values. Thanks
$query=sprintf("SELECT ID,NAME FROM USERS WHERE PASS='%s' AND NAME='%s'",mysql_real_escape_string($p),mysql_real_escape_string($n));
$result=mysql_query($query);
if ($result)
{
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'];
echo $row['NAME'];
}
}
}
Some simple questions to start with:
Have you done a var_dump($row) to see what it returns?
Are you sure that the name and the password you specify are actually in the database?
Have you encrypted the password in the database (and not in the query)?
Have you a valid database connection ? (I know the answer is yes but a double check won't harm anyone and maybe save some headache)
Edit:
Added a link to the man page for var_dump.
As already suggested use mysql_error() to find what goes wrong. (A simple echo mysql_error(); after $result=mysql_query($query); will suffice)
write down out the query to see if something goes wrong with the escaping.
1.Echo out Your $query to see if it is what You like to be for debugging purposes;
2. Check $row['ID'] AND ['NAME'] if they are really UPPER letters;
3. Use mysql error reporting after if ($result){....} else { echo mysql_errno($link) . ": " . mysql_error($link) . "\n"; } where $link is Your DB handle.
Are you sure that rows were returned? You can use mysql_num_rows($result) to get the count. The only thing I can think of looking at your code is that you're passing in the password in plain text and the version in the DB is MD5 or something.