PHP - Unable to retrieve data from the database - php

For some reason, the query when run through PHP will not return the results. I have tried both queries in the MySQL command line, and they work perfectly there. Here is the code (mysql_connect.php is working perfectly, to clarify).
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
When I run the script, I get the message "could not get id", yet that query works in the MySQL command line and PHPMyAdmin.

Your code won't work for 2 reasons - $id will not magically turn into integer, but a mysqli result. And email is a string so it should be quoted.
But...
Why is all of that?
If you want to fetch all the data for user, for certain email, just make you second query fetch data by email and remove the first one:
SELECT * FROM users WHERE email='$email';
And don't forget to escape your input, because it's in cookie. Or, use prepared statements as suggested.

Your query is not valid, you should rewrite it with the following and make sure your you have mysqli_real_escape_string of the $email value before you put it into queries:
SELECT user_id FROM users WHERE email='$email'
Better approach is to rewrite your queries using MySQLi prepared statements:
Here how to get the $id value:
$stmt = mysqli_prepare($dbc, "SELECT user_id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);

You wrote
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email");
that is similar to
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=example#example.com");
but it should be
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='example#example.com'");
so you have to do this
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='$email'");
or better
mysqli_query($dbc, 'SELECT user_id FROM users WHERE email=\'' . $email . '\'');
Beside this minor bug
You should be aware of SQL injection if someone changes the value of your cookie.

Related

Prepared statement returns no results

I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
echo $stmt->num_rows." ".$username;`
The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query
$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;
Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.
num_rows will be populated only when you execute $stmt->store_result();.
However, 99.99% of the time you do not need to check num_rows. You can simply get the result with get_result() and use it.
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
// ...
}
If you really want to get the num_rows, you can still access this property on the mysqli_result class.
$result = $stmt->get_result();
$result->num_rows;
You've executed the query successfully, but not done anything with the result. After $stmt->execute();, you're looking for $stmt->bind_result($result);.
With this, you'll have access to the user's information in the $result variable.

Why is my mysqli_fetch_assoc not grabbing the row info so I can insert details into my table?

First off, I know about sql injection and that my code is not foolproof, prone to injection etc. Will be working on that next.
Now : from my Android app to my PHP file I submit a JSON array of phone numbers like :
[{"phone_number":"+12345678"},
{"phone_number":"+23456789"},
{"phone_number":"34567890"},
{"phone_number":"45678901"}
etc... etc...
These are contacts in my app user's phone. If these contacts are people who are also users of my app then I want to insert those numbers into my contacts table.
But I can't get it to work. mysqli_fetch_assoc isn't working correctly. I don't know why.
In my contacts table I have 3 columns - an auto increment, user_id and contact_id. The first two values are inserted correctly but the contact_id is always put in as '0', which is wrong.
Here is my code :
require('dbConnect.php');
//this is me, +567890123, my user_id in the user table
$user_id = '20';
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumber'];
$array = json_decode($json);
foreach ($array as $value) {
$phonenumber = $value->phone_number;
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
echo "phonenumber is " . $phonenumber . "<br>";
// we want to put $phonenumber in the contacts table, as one of +567890123 contacts
// In the user table get the associated rows of $phonenumber
while ($row = mysqli_fetch_assoc($result)) {
// get the associated user_id in that row, that's what we want to put into the contacts table
$contact_id = $row['user_id'];
$insert_into_contacts_command = "INSERT INTO contacts VALUES(NULL, '$user_id','$contact_id')";
$insert_into_contacts_table = mysqli_query($con, $insert_into_contacts_command);
}
} //if +353864677745 is NOT in the user table...
else {
echo 'not a match.';
}
}
$contact_id = $row['user_id'];
Here $contact_id will be null, because you are trying to access not existing field $row['user_id'] of the $row .
Actually there is only one field username in your results set, as you specified:
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
Try to change your query to this:
$sql = "SELECT user_id, username FROM user WHERE username = '$phonenumber'";
Your query selects the column username, not userid.
You haven't posted anything about the table user, so it's hard to suggest a new query, but I guess it's the following:
$stmt = mysqli_prepare($con, "SELECT userid FROM user WHERE username = ?");
$stmt->bind_param("s", $phonenumber);
$stmt->execute();
$stmt->bind_result($userid);
while ($stmt->fetch()) {
// Work with $userid
}
You'll note that this uses a prepared statement with a bound parameter. That way, your code is not prone to SQL injections.

How to use one stmt query inside another

i have to get data from one table from my database, BUT after getting the data, i have to access another table to get more data using the id found in the first query.
Here is my code:
$query = "SELECT id,name,datetime FROM table1 WHERE id=?";
if($stmt=mysqli_prepare($mysqli,$query)){
mysqli_stmt_bind_param($stmt,"i",$_SESSION['id']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$datetime);
while(mysqli_stmt_fetch($stmt)){
$query2 = "SELECT id FROM table2 WHERE id=?";
if($stmt2=mysqli_prepare($mysqli,$query2)){
mysqli_stmt_bind_param($stmt2,"s",$id2);
mysqli_stmt_execute($stmt2);
mysqli_stmt_store_result($stmt2);
$num = mysqli_stmt_num_rows($stmt2);
}
The code does not work, i know i can't do that. I'm new with mysqli, in MySQL it works, but in MySQLi don't.

sanitize using {$_GET['id']} doesn't display mysql info

I am trying to sanitize my $_GET input but for some reason, mysql doesn't retrieve the data from the DB. If I do this:
$user = mysqli_real_escape_string($connection, $_GET['id']);
//execute query to call user info
$query = "SELECT user
FROM company
WHERE user={$_GET['id']} ";
this will work and the results are displayed; however if I do this:
$user = mysqli_real_escape_string($connection, $_GET['id']);
//execute query to call user info
$query = "SELECT user
FROM company
WHERE user= '$user' ";
I don't get a database error, but nothing shows up.
Am I not sanitizing right? What's going on here? HELP, please!
Best way to avoid such situations is using prepared queries:
How can I prevent SQL injection in PHP?
It's very simple and effective:
$q = $db->prepare('SELECT user FROM company WHERE user=?');
$q->bind_param('i', $user);
$q->execute();
$result = $q->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
It's cool because it's OOP and it's safe. Some links:
Connection to DB
Prepare statement
Bind parameters

mySQLi Prepared Statement Select with Escape Characters

I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()

Categories