Unable to fetch user data from mysql database - php

I am attempting to access user data from a single table in mysql in order to display it on the screen.
eg. "Logged in as 'username'."
I have followed the instructions from this tutorial.
This is my function:
//create function to fetch user data (eg. username, firstname, address, etc.)
function fetchUserData($field) {
$user_id = $_SESSION['user_id'];
$query = "SELECT '$field' FROM users WHERE id = '$user_id'";
if ($query_run = mysql_query($query)) {
if ($query_result = mysql_result($query_run, 0, $field)) {
return $query_result;
}
}
}
And I'm calling the function like so:
$firstname = fetchUserData('firstname');
$surname = fetchUserData('surname');
echo 'Logged in as '.$firstname.' '.$surname.'.';
The $_SESSION['user_id'] is working, I have tested it. But i am unable to collect the data (username, address, etc.) that correlates with that user's id.
Furthermore, $query_run is returning resource ID #7, whatever that means??

change your single quotes around $field
$query = "SELECT '$field' FROM users WHERE id = '$user_id'";
to backticks
$query = "SELECT `$field` FROM users WHERE id = '$user_id'";
^ ^
Also, you do not have mysql_connect() shown, so most likely you have a variable scope issue - http://php.net/manual/en/language.variables.scope.php - so your query is failing as there is no connection. You can verify this by using or die(mysql_error()) -
if ($query_run = mysql_query($query) or die(mysql_error()) {
or
if ($query_run = mysql_query($query)) {...}
else{die(mysql_error());}

if ($query_result = mysql_result($query_run, 0, $field)) {
return $query_result;
}
should be
if ($query_result = mysql_result($query_run, 0)) {
return $query_result;
}
or you may use
if ($query_result = mysql_result($query_run, 0, "'".$field."'")) {
return $query_result;
}
add single quote to the $field

Related

my function that checks if something is already in the database isn't working

I'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.

Mysql_result .. not showing data

function getfield($get){
global $connection;
$query = "SELECT id, username, firstname, lastname FROM users WHERE username='".$_SESSION['user_id']."'";
if ($query_r = mysqli_query($connection, $query)) {
$num_rows = ($query_r -> num_rows);
if ($mysqli_result = mysqli_result($query_r, 0, $get)) {
return $mysqli_result;
}
I made a log in form and now all working fine but this function don't showing data. I think mysql_result not working in 7.1.
function getfield($get){
global $connection;
session_start();
$query = "SELECT id, username, firstname, lastname FROM users WHERE username='".$_SESSION['user_id']."'";
if ($query_r = mysqli_query($connection, $query)) {
$num_rows = ($query_r -> num_rows);
if ($mysqli_result = mysqli_fetch_assoc($query_r)) {
return $mysqli_result;
}
}
The function mysqli_result does not exist, so you would need to use something like mysqli_fetch_array(). Replace your innermost if-clause with this:
if ($mysqli_result = mysqli_fetch_array($query_r)) {
return $mysqli_result[$get];
}

PHP: find out the primary key of the just-inserted row data

I'm trying to find out the id value which is the primary key of the table. In order to do so, I implemented a code like this.
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$result = mysqli_query($this->db->connect(), $query);
$id = mysqli_insert_id($this->db->connect());
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}
Here I tried to get the id by running thhe $id = mysqli_insert_id($this->db->connect()); command, but it doesn't seem to work.
Any solutions?
You need to use a connection variable not a function call. A second call to connect() is returning a new connection.
$connection = $this->db->connect();
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);
Or if you keep a variable in the db class which makes sense:
$result = mysqli_query($this->db->connection, $query);
$id = mysqli_insert_id($this->db->connection);
Save the connection
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$con = $this->db->connect();
$result = mysqli_query($con, $query);
$id = mysqli_insert_id($con);
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}

mysql_query() failing very oddly

This is a really simple thing, but it's not working for some reason. Heres my code.
I am making function (its part of a class) which checks if a username or email exists:
public function exists ($what, $who)
{
$sql = "SELECT * FROM users WHERE $what = $who";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 0)
{
return true;
}
else
{
return false;
}
}
The function returns nothing. In fact if I run that query through regular PHP it returns nothing also. I don't understand why.
This following piece of code returns news entries perfectly:
function fetch($id = '')
{
if (empty($id))
{
$query = 'SELECT * FROM news ORDER BY id desc';
}
elseif (is_numeric($id))
{
$query = "SELECT * FROM news WHERE id = $id";
}
else
{
$route->to(SITE_URL);
}
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
return $result;
}
}
I am confused.
The problem is that you are missing quotes in your query:
$sql = "SELECT * FROM users WHERE $what = $who";
//SELECT * FROM users WHERE username = Mario is not a valid query
should be:
$sql = "SELECT * FROM users WHERE $what = '$who'";
the other queries are working because you are checking against an id, in this case against a string (and in this case you need quotes)
maybe the query execution failed and you have error turned off on screen in your php.ini
Try to add an intermediate check on the correct execution of the query:
$query = mysql_query($sql);
if ($query === FALSE) {
// log error with mysql_errno($conn) and mysql_error($conn);
} else {
if (mysql_num_rows($query) != 0) {
return true;
etc. etc.

PHP: Making this grabbing from db easier/simpler way?

Is there any method i could do this easier:
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
as i only need to grab the full_name, then i make a var for the fetch_array and so, is there any way to make this simpler and echo? There was something about list(), but im not sure..
Ignoring possible security breaches and the usefulness of a DAL (see #deceze's answer), I recommend the use of mysql_result() instead of mysql_fetch_assoc() (or *_array() or whatever):
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$fullName = mysql_result($query, 0);
echo $fullName . " ";
Not easier per se but should be more in line with the intention of the query (fetch one field in one row).
The only way to abstract this any more and thereby make the actual call shorter is by using a DAL and/or ORM like Doctrine or Propel, which you should anyway.
May be not easier, but more securely:
$id = mysql_real_escape_string($show['uID']);
$query = mysql_query("SELECT `full_name` FROM `users` WHERE id = '".$id."'");
$row = mysql_fetch_array($query);
echo $row['full_name'];
Oh you can to make id with intval:
$id = intval($id);
This could make further DB-questions easier;
function mysql_fetch_scalar($res)
{
$arr = mysql_fetch_array($res);
return $arr[0];
}
$query = mysql_query("SELECT full_name FROM users WHERE id = '".intval($show[uID])."'");
$fullname = mysql_fetch_scalar($query);
echo $fullname . " ";
Sure.
Moreover, you should - to make a function out of these repetitive API functions calls.
Something as simple, as this
function dbgetvar($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
have this function in your config file and use every time you want a value from database:
echo dbgetval("SELECT full_name FROM users WHERE id = '$show[uID]'");
(I hope you have $show[uID] escaped)
Of course there can be also 2 similar functions, to return a row or a rowset. Or just one but with additional parameter. Or you can combine them into class...
You can make it even escape variables for you:
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
echo dbgetvar("SELECT full_name FROM users WHERE id = %s",$show['uID']);
That's what you have to do. You could wrap that in a helper function if you're using it a fair bit, but then you'd probably want to cache the answer you get - I don't suppose the name changes all that often...
function echoName($user_id) {
$id = mysql_real_escape_string($user_id);
$query = mysql_query("SELECT full_name FROM users WHERE id = '$id'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
}
// ...
echoName($show['uID']);

Categories