MYSQL SELECT query does not work - php

I want to select email address from DB to send a email. Following is my query that I have made.
$userID=$_SESSION['userID'];
$select_query = mysql_query("SELECT * FROM employee WHERE emp_id = '$userID'");
$select_sql = mysql_fetch_array($select_query);
$name=$select_sql['manager_name'];
$select_query1 = mysql_query("SELECT email FROM employee WHERE employee.name='$name'");
$select_sql1 = mysql_fetch_array($select_query1);
$email=$select_sql1['email'];
But $select_query1 return "NULL Invalid address:" instead of the correct value. I could not found the problem with this. Please help !

You are using $_SESSION['userID'] to get all data from table employee so instead of doing two queries simply try this
$empID = $_SESSION['userID'];
$query = mysql_query("SELECT * FROM employee WHERE emp_id=$empID");
$result = mysql_fetch_array($query);
$email = $result['email'];

Related

How to set result SQL distinct query to one or different variables?

I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.

select values from different columns mysql, how do I tell which is which?

$sql = "SELECT email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$email1 = $row[0];
$email2 = $row[1];
Just trying to select email from 2 columns and identity which email belongs to which username. Email1=user1 and email2=user2, is what I seek.
$sql = "SELECT username,email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($query))
{
$email[ $row[0]] = $row[1];
}
mysqli_free_result($row);
Hope it will help..
expected output
$email['user1']= email1
$email['user2']= email2
As written, each row would contain only a single email address.
You'd be better served selecting an additional column that identifies the user, such as an id or username.
Then each row would contain both the email and the identifying data associated with that email. If more than one row is matched, you'll need to fetch additional rows to determine that, or else use an aggregate query.
$sql = "SELECT username,email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($query)){
$username = $row[0];
$email = $row[1];
// do some checking
}
Also, be sure the values of $user1 and $user2 are safe before sending...

PHP link with SQL Database

New to PHP here. I'm working on a basic PHP project for university. I have a page with a list of patients. When you click on the patient it will take you to the patient page with more details of that patient.
I have a main patientDetails.php page which will display the details.
However I am a little puzzled. How do I get the "?Name.." part of the link to work. So how do I get the patientDetails page to load the specific patient details?
I have an index.php page which has the list of patients as below.
<td>Stuart</td></tr><tr> <td>2</td>
<td>Fred</td></tr><tr>
In the PatientDetails page I have a select statement to gather details from the Database but not sure where else to go from here.
$query = sprintf("select * from PHPEnrolment WHERE PatID = '$PatID' AND NAME = '$Name' AND Email = '$Email'");
$result = mysql_query($query, $link);
if ($result) {
while($row = mysql_fetch_array($result)) {
}
As you can see above the database table with patients has the PatID, Name and Email field.
Thanks
PLEASE NOTE: This is a basic project that I am working on, so I am aware some of the features are outdated but I need to get it working with these features if possible.
You can get the url variables using $_GET. I see that you are passing only Name parameter in the url. Use the below code.
$name = $_GET['Name'];
$query = "select * from PHPEnrolment WHERE NAME = '$name'";
$result = mysql_query($query, $link);
if ($result) {
while($row = mysql_fetch_array($result)) {
// display details here
}
}
As per your code there are several errors. and for getting value you can use $_GET['Name']. I am assuming that you have all other variables($Email and $PatID)
$Name = $_GET['Name'];
Your query is not right. Change it from
select * from PHPEnrolment WHERE PatID = '$PatID' AND $NAME = 'Name' AND Email $Email
To
select * from PHPEnrolment WHERE PatID = '$PatID' AND NAME = '$Name' AND Email = '$Email'
So your whole code should look like.
$query = "select * from PHPEnrolment WHERE PatID = '$PatID' AND NAME = '$Name' AND Email = '$Email'";
$result = mysql_query($query, $link);
NOTE : STOP USING MYSQL. It is deprecated now.

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

PHP fetching data from MySQL database

So I'm trying to fetch data in a many-to-many relationship.
So far I have this, which finds the user:
$user = $_SESSION['user'];
$userID = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
And I know that to echo this information I have to put it in an array like so:
while ($r = mysql_fetch_array($userID)) {
echo $r["0"];
}
This works fine, but when I try to find this variable in another table, I'm not sure what to use as the variable:
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='???'") or die(mysql_error());
I've tried replacing ??? with $userID and $r, but to no avail. I know the code works because it's fine when I put a user ID in manually - where have I gone wrong?
$user = $_SESSION['user'];
$query = mysql_query("SELECT * FROM users WHERE user='".mysql_real_escape_string($user)."' LIMIT 1") or die(mysql_error()); //--note the LIMIT
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='$userID'") or die(mysql_error());
Untested, but this should work:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users
WHERE users_ID='$userID'") or die(mysql_error());
I your case, you'd need to place $r[0] there.
I think this code is helpful for beginners when you want to get data in array form
we use mysqli instead of mysql to protecting your data from SQL injection.
Before use this code check the database connection first
<?php $tableName='abc';
$qry="select * from $tableName";
$results=mysqli_query($qry);
while($records=mysqli_fetch_array($results))
{
$firstrecord=$records[1];
$secondrecord=$records[2];
}
?>
You can get your projects with one query:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT pu.projects_ID FROM users u
INNER JOIN projects_users pu ON (pu.users_ID = u.users_id)
WHERE u.user='$user'") or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['projects_ID'];
}

Categories