I am trying to create a duplicate username checker and I am thinking this is probably the way to do it correct me if im wrong. Basically I want the username the user input to be stored in a variable called userName and then use that variable to check and see if there are any LIKE rows in the database and if so return a count of 1 or more to a variable named $count I would then have an IF ELSE statement that would either yell at the user or let them continue. I have run into a problem using the LIKE statement. I think my syntax could be wrong since I have been trying several different methods but still no luck.
Main Code
<?php
require 'DB.php';
$userName = "tes";
echo $userName;
try{
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name` LIKE "% . ":userName" . "');
$stmt->bindValue(':userName', $userName);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
echo $count;
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
?>
It appears you're trying to do string concatenation in MySQL using invalid syntax. Try this:
'SELECT COUNT(*) FROM `CLL_users` WHERE `user_name` LIKE CONCAT("%",:userName)'
You can probably use = instead of LIKE. The SQL syntax in itself isn't case-sensitive. I think you might be able to set up your database so that certain tables are case sensitive but I know for a fact through usage that no tables in my own MySQL database are. If you're unsure it's easy to try, just run a select with a username you know is in there but write it with different casing.
Just do a select WHERE 'user_name'=$entered_username, if you get one or more don't add the new user, if not go ahead. You could of course mark the user_field as unique, that way you'd know for sure you won't have duplicates, might be something worth looking at.
Try to use this select:
("SELECT COUNT(*) FROM CLL_users WHERE user_name LIKE "% . "'".$userName."'");
Related
I'm having the problem of mySQL not recognizing the session user when I select data from a table. Can someone please point me in the correct position on what I need to do to fix this?
$sql1="SELECT * FROM `Bookings` WHERE `username`={$_SESSION['user']}";
This is what my code looks like, but it never fetches the data and just remains blank.
First you should check if $_SESSION['user'] is initialized or has any value.
Second, it is better to assign the session user to a variable, so as to avoid some ugly issues related to escaping quotes, in the future. Don't just directly dump your session within your mysql statement.
$user_session = $_SESSION['user'];
$sql1="SELECT * FROM `Bookings` WHERE `username`= $user_session";
#Edit:
as #Dann pointed out, it's must better and safer to user prepared statement, with either the mysqli/pdo API. Here is a simple example in PDO.
First you have to connect to your database:
try {
$db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
echo "Error connecting to mysql: ". $e->getMessage();
}
Then simply fetch the booking as seen below.
$user_session = $_SESSION['user'];
try{
$stmt = $db->prepare("SELECT * FROM Bookings WHERE username = ?");
$result = $stmt->execute([$user_session]);
if($result){
// show booking
}
} catch(\PDOException $e){
echo "Counld not get user bookings. error: " . $e->getMessage();
}
Now your query is safer from mysql injection attacks, and connection errors will only throw exceptions, instead of showing potentially harmful errors.
You can use
$user=$_SESSION['user'];
$sql1="SELECT * FROM Bookings WHERE username= '$user'";
Hopefully This will solve your problem
I was advised to update my code to prevent sql injections. So here is what I have.
VARIABLE FROM URL
$Idarticle = "5-6142-8906-6641";
THIS WORKS - OLD
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ('{$Idarticle}')";
$results2 = $conn->query($sql2);
$row2 = $results2->fetch_assoc();
THIS DOES NOT WORK - NEW
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
$row2 = $stmt->fetch();
}
MY CONNECTION SCRIPT
$conn = new mysqli($servername, $username, $password, $db);
In the second example I get no results(no errors either) verses in the first it finds the correct row. I have read numerous similar questions previously asked and while there may be an answer out there, I did not find it. I also tried some of those answers without any success. I appreciate any help.
UPDATED CODE PER COMMENTS
$sql2 = "SELECT * FROM articles WHERE IDArticle = ?";
if (!$stmt = $conn->prepare($sql2)) {
if (!$stmt->bind_param("s", $Idarticle));
echo "error: " . $stmt->error;
if (!$stmt->execute());
echo "error: " . $stmt->error;
$row2 = $stmt->fetch();
}
Still not finding the record / no errors being reported
MY SOLUTION
Having spent close to two days researching and trying to solve this issue, I decided mysqli was at the heart of the problem. Why I am sure this issue does have a solution with mysqli, I ended up moving to PDO. I resisted doing this initially but after a few hours of study, it is in my opinion, as well as many others, far better. Bottom line it now works flawlessly with very few changes. My recommendation, If you are struggling with mysqli, switch to PDO.
A BIG THANK YOU TO THOSE WHO TRIED TO HELP
BTW: Is there any special reason for using IN?
"SELECT * FROM articles WHERE IDArticle = ?"
This is your problem:
$row2 = $stmt->fetch();
mysqli_stmt::fetch returns boolean true/false on success, and you're trying to use it as an array for row2
You must bind your results first with mysqli_stmt::bind_result, and then fetch
See this creative answer for how to get an associative array from bind_result
Preferably, if you have the MySQL native driver installed, then you can extract this directly with mysqli_stmt::get_result
Also, you're not checking for statement errors.
if ( !$stmt->bind_param("s", $Idarticle) )
echo "error: " . $stmt->error;
if ( !$stmt->execute() )
echo "error: " . $stmt->error;
And you should make sure you're using PHP error reporting.
If $results1/$results2 is not a typo, then the new code is very different, because there must be two independent queries.
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
}
But it's not clear then what was done with $results2 later in the code. row2 might be totally unrelated to
$row2 = $results1->fetch_assoc();
The code below is part of a simple password manager. I get an error saying the Query is empty yet the query works just fine in MySQL. (The 1 and the test value were originally variables I just changed them to values as part of my troubleshooting). I am also aware that the column names user and password may be problematic, but I added ` around them. What else could be wrong with that code?
$change_pass_query = "UPDATE `user` SET `password` = PASSWORD('test') WHERE id = 1";
$change_pass_result = mysql_query($change_pass_query) or die('Error. Change Password Query failed: '. mysql_error());
Try formatting your SQL like this:
UPDATE `user` SET `password` = 'test' WHERE `id` = 1
http://php.net/manual/en/function.mysql-query.php
Notice the warning at the top of that page. Nobody uses mysql_query or any plain mysql functions. Research mysqli/mysqli_query, and PDO.
Here's how you could do this with PDO:
$pdo = new PDO("mysql:host=localhost;dbname=mydb","username","password");
$stmt = $pdo->prepare("UPDATE `user` SET `password` = PASSWORD(:password) WHERE id = :id");
$result = $stmt->execute(array(':password' => "test",':id' => 1));
if (!$result) die('Error. Change Password Query failed: '. mysql_error());
Here's some documentation on PDO: http://php.net/manual/en/book.pdo.php
I ended up renaming all tables and fields so that I didn't use any reserved words, as I thought that the issue might be that. The problem still happened. I then copied my code to a different PHP box, et voila, the code works just fine. I'll have to put it down to an issue with the PHP version/installation on the older box and move on. There is nothing wrong with the code.
I'm sure there are very similar questions to this one on here but upon doing countless searches like this, all I have been coming up with is ones for other languages other than PHP or slightly different constructs that throw off what I am trying to do and causes errors. SO please excuse me if it sounds a little redundant.
I have the following code that enters data into the MySQL databse just fine and works...
mysql_connect("" . $db_server_name . "", "" . $db_username . "", "" . $db_password . "") or die(mysql_error()); mysql_select_db("" . $db_database_name . "") or die(mysql_error());
mysql_query("INSERT INTO users (fb_id,fb_name,fb_first_name,fb_last_name,fb_profile_link,fb_username,fb_birthday,fb_gender,fb_email,fb_locale,reg_date,app_points,app_submissions,app_sub_available,app_wins) VALUES ( 'item','item','item','item','item','item','item','item','item','item','item','item','item','item','item' )");
echo "Your table has been populated";
But I simply want the following...
To check and see if the fb_id already exists (which is known locally as $user_id variable) ...in other words it will see if $user_id already exists in the tabe where fb_id is.
Insert the data (from the working code above) if it does not exist.
Print "It already exists" if it does exist.
I know this seems like a simple fix for many of you but oddly enough, I have never had to do this before so it's not so simple for me.
Thanks A Bunch for your time!
$data = mysql_query("SELECT * FROM table_name WHERE fb_id = $fb_id") or die(mysql_error());
if(!mysql_num_rows($data)){
mysql_query("INSERT INTO users (fb_id,fb_name,fb_first_name,fb_last_name,fb_profile_link,fb_username,fb_birthday,fb_gender,fb_email,fb_locale,reg_date,app_points,app_submissions,app_sub_available,app_wins) VALUES ( 'item','item','item','item','item','item','item','item','item','item','item','item','item','item','item' )");
echo "Your table has been populated";
}esle{
echo "Id Already exist!";
}
so why not do a "select fb_id as user_id from users where fb_id=$user_id" then if that returns no rows do the insert.
After I upload a photo to a server, I want to save it in the user's database in MySQL, but for some reason, it is not working. Below is the code for uploader.php:
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
$con = mysql_connect("host","db","pw");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE fldID='$sess_userid' UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'");
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result);
I'm sure there is something very wrong with my query, but I can't figure out what it is. The photo is definitely being saved into the folder. But I simply want to update its path in the user database for later use. Thank you!
as it was mentioned already, you cannot use these two queries at once.
but there is also weird syntax: you're trying to use PHP's concatenation operator inside of mysql query.
And you did not escape a string parameter - very bad!
So, looks like you need something like
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$PortraitPath = mysql_real_escape_string('profileportraits/' . $_FILES['file']['name']);
$query = "UPDATE Members SET PortraitPath = '$PortraitPath' WHERE fldID='$sess_userid'";
You can do two separate queries:
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'
WHERE fldID='$sess_userid';
And:
SELECT * FROM Members WHERE fldID='$sess_userid'
It seems you tried to put two queries(SELECT and UPDATE) into one query which will result in invalid query error.
Just wondering why you need two queries since you already know the userid and all you want is to update. All you need is to update the file path
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]' WHERE fldID='$sess_userid';