I am using a variable in my php code named $user_id. This variable takes a value after executing a short script of code. I also have a table named users in my database and this table holds user_id and email. If want to select email from my database, when the user_id from my table is equal to my variable named $user_id. Can I do this? This is my query:
<?php
//code ...
$user_id=$_GET['user']; //$user_id gets a value here
//now I want to select email from table users, where user_id is equal to variable $user_id
mysql_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
?>
Yes, it will work. I'd though advise you to use pdo or mysqli instead of mysql_* functions. They have been deprecated.
If for some reasons you can not switch to either of them; you should filter/sanitize your query.
Also, if user_id is a numeric field, you wouldn't be needing to enclose $user_id in quotes.
Your code has the basics, it just needs handling and I would add a couple of checks.
if(isset($_GET["user"]) && $_GET["user"] != "") //check there is a value for the user ID
{
if(is_int($_GET["user"]))
{
$user_id=$_GET["user"]);
$email="";
$q=mysql_query("SELECT email FROM users WHERE user_id={$user_id}") or die(mysql_error());
if(mysql_num_rows($q) > 0)
{
while($user=mysql_fetch_assoc($q))
{
$email=$user["email"];
}
}
else
{
echo "no users found";
}
}
else
{
echo "Not a valid user ID, please enter numeric value";
}
}
else
{
echo "No UserID";
}
hjpotter92 recommends that you use mysqli or pdo for questioning your database, which I would agree with although while learning keep with mysql as there are more resources available for learning, then when confident move onto newer technologies.
Please note: I have based this on the experience I feel the user has got with PHP and MySQL not on the most modern or best practices.
The code should be:
$email = '';
$res = mysqli_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
while ($temp = mysqli_fetch_assoc($res)) {
$email = $temp['email'];
}
Related
I'm trying to check an email against my database, and if it doesn't already exist, add it to the database.
$query = "SELECT * FROM users";
$inputQuery = "INSERT INTO users (`email`,
`password`) VALUES ('$emailInput',
'$passInput')";
$emailInput = ($_POST['email']);
$passInput = ($_POST['password']);
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
if ($row['email'] == $emailInput) {
echo "We already have that email!";
} else {
mysqli_query($link, $inputQuery);
echo "Hopefully that's been added to the database!";
}
}
};
It can detect an existing email, it's just the adding bit...
Currently this seems to add a new empty row for each existing row (doubling the size).
I'm trying to understand why it doesn't add the information, and how to escape the loop somehow.
Also for good measure, everyone seems to reuse $query, but this seems odd to me. Is it good practice to individually name queries as I have here?
Please let me know if there's anything else I should add.
I am not going to talk about the standards but straight, simple answer to your question.
Approach - 1:
INSERT INTO users (`email`,`password`) SELECT '$emailInput', '$passInput' from DUAL WHERE NOT EXISTS (select * from users where `email` = '$emailInput');
Approach - 2:
- Create a unique key on email column
- use INSERT IGNORE option.
user3783243 comments are worth noting
Try this :
$emailInput = mysqli_real_escape_string($link, $_POST['email']);
$passInput = mysqli_real_escape_string($link, $_POST['password']);
$qry3=mysqli_query($link,"select * from users where `email`='".$emailInput."'");
$num=mysqli_num_rows($qry3);
if($num==1) {
echo "Email-Id already exists";
} else {
$inputQuery = mysqli_query($link,"INSERT INTO users (`email`, `password`) VALUES ('".$emailInput."', '".$passInput."')");
if ($inputQuery) {
echo "Hopefully that's been added to the database!";
}
}
Your code seems to be a bit over-engineered because why not to pass you $_POST['email'] to select query where clause
"SELECT * FROM users where email = $emailInput" and then check if it is there already.
Also, keep in mind that this is an example only, and you should always check and sanitize user input.
From another hand you can do it with MySQL only using INSERT ... ON DUPLICATE KEY UPDATE Syntax. https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
That requires to add unique key for email column.
I have two issues and both are linked. First, "already booked - please select another date" is not appearing, if two clients select the same product (pg_no) and date (Date). These fields are UNIQUE CONSTRAINT.
Second, when data is inserted or submitted localhost shows complete address
http://localhost/lstcomp/index.php?note=submitted. But when it fails the localhost shows only : http://localhost/lstcomp/
<?php
//connecting string
include("dbconnect.php");
//assigning
$name = $_REQUEST['Name'];
$tele = $_REQUEST['Tele'];
$city = $_REQUEST['City'];
// UNIQUE CONSTRAINT
$pg_no = $_REQUEST['pg_no']; //product
$date = $_REQUEST['Date']; //date
//checking if pg_no and Date are same
$check = mysqli_query($db_connect, "SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
mysqli_close($db_connect);
// messaging
if ($query) {
header("location:index.php?note=failed");
} else {
header("location:index.php?note=success");
}
?>
There are a few problems:
The file fails to parse because of the dangling else; it's not paired with an if-statement.
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
It looks like you're intending to use the result from your SELECT statement ($check), however...
The SELECT statement is invalid; WHERE clauses are separated with AND or OR, not commas.
When inserting the row into the database table, you're dying on mysql_error when you've been using the mysqli extension.
You're vulnerable to SQL injection attacks; if pg_no happened to be '; DELETE FROM users; --, as an example, your user table would be deleted. You're already using the mysqli extension, so use parameter binding and prepared statements. Reference
I am a little confused about how $query works and how I can find a value... Say I have a checkuser.php script. The purpose here is to echo "Correct" if the user already exists. I have the columns (username, password, email). What I want to know is how can I search the column username for value $username? This is what I have currently:
$query = sprintf("SELECT * FROM users WHERE CONCAT(username) LIKE '$u'");
$result = mysql_query($query);
if(mysql_num_rows($result) != 1)
echo "Username Not Found";
Thanks!
This should work. However, I didn't test it:
$query = "SELECT * FROM users WHERE username = '$u'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
echo "Username Not Found";
In your query, you do not need to use the sprintf() function at all. an SQL query is inserted as a regular string.
Furthermore you don't need to use CONCAT() SQL function either.
Then if you want to check against an exact string you can just compare with the = operator instead of using SQL LIKE statement.
I haven't tested it, but this should work:
$q=mysql_query("select ysername from user where username='$u'");
$count=mysql_num_rows($q);
If ($count>0) { echo "usename fount";};
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
if($_SESSION['usergroup']==1) { //admin
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else if($_SESSION['userid']==1013) { //managers
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else { //everyone else
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
so what i would like to do is to change this line here:
else if($_SESSION['userid']==1013) {
i want to check if the logged in user has a value of 1 in the user_table in a field called manager. the pseudo code would be something like:
else if(user_table manager field == 1) {
or
else if(if logged in user has a value of 1 in the manager field of the user_table table) {
does this sound like something that can be done?
what i'm trying to accomplish is to edit users and make certain users managers, but i don't want to have to keep editing php files to keep adding those new users every time i make a user a manager. i just want the users that have been upgraded to have access to that middle query automatically.
here is what i don't want to do...
else if($_SESSION['userid']==1013 || $_SESSION['userid']==1014 || $_SESSION['userid']==1015 || $_SESSION['userid']==1016) {
...and keep adding and adding to this line in this fashion.
That definitely sounds like something that can be done. I would use something like this, using PDO to prepare and then execute the statement.
//Prepare the SQL query, using the :user_id parameter which you'll supply in the next statement
$stmt = $con->prepare('SELECT manager FROM user_table WHERE userid = :user_id');
//Execute the SQL, supplying the parameter
$stmt->execute(array(':user_id' => $_SESSION['userid'])'
//Retrieve the value
$manager_role = $stmt->fetchColumn();
Or, you can do the same thing without using PDO by preparing your SQL query before running it.
$sql_query = 'SELECT manager FROM user_table WHERE userid = ' . $_SESSION['userid'];
$manager_role = = mysql_query($sql_query);
....
//Your original code
if($_SESSION['usergroup']==1) { //admin
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else if($manager_role == 1) { //managers
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else { //everyone else
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
....