Returning array from simple function is empty - php

I have the following function:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = $ru->fetch_array();
return $user;
}
Which is called eg:
$user_id = $_SESSION[user_id];
getUser($user_id);
Then I want to simply echo fields i want, e.g. name. But, when I try the following, it returns empty
echo "users name is $user['name']"; // returns: users name is
Is there a better way to do this?
UPDATE Also tried the following but still empty:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = array();
while($row = $ru->fetch_array()) {
$user[] = $row;
}
return $user;
}

your line:
getUser($user_id);
should be:
$user=getUser($user_id);
This way you'll be setting $user to the array the getUser returns, then you can use it.

Remove the single quotes when printing an array, you echo may needed to be like:
echo "users name is $user[name]";

Related

Using two SELECT queries in php database connection

here is my_sqli database connection
class FbChatMock {
// Holds the database connection
private $dbConnection;
private $_dbHost = 'localhost';
private $_dbUsername = 'root';
private $_dbPassword = '';
public $_databaseName = 'erp5_temp2';
public function __construct() {
$this->dbConnection = new mysqli($this->_dbHost, $this->_dbUsername,
$this->_dbPassword, $this->_databaseName);
if ($this->dbConnection->connect_error) {
die('Connection error.');
}
}
i am getting two parameters in the getchat function:
public function getchat($userId, $id){
$meesage = array();
$query = "SELECT u.user_id FROM `users` u where u.id='$id'";
$resultObj = $this->dbConnection->query($query);
$user = $resultObj->fetch_assoc())
$userid = $user;
}
I am getting the $userid variable from the query and using it inside this query:
$query = "SELECT u.id,c.message,c.sent_on FROM `chat` c JOIN
`users` u ON c.user_id=u.user_id where u.id='$id' AND c.user_id='$userid'";
// Execute the query
$resultObj = $this->dbConnection->query($query);
// Fetch all the rows at once.
while ($rows = $resultObj->fetch_assoc()){
$meesage[] = $rows;
}
return $meesage;
And the problem is that my first sql query is not working correctly . i have tested it by showing $userid value from echo.
Chage this line
$userid = $user;
To this
$userid = $user['user_id'];
Because $user it is array with all columns you have selected, and you need get only ID from it.
Your problem lies here :
$user = $resultObj->fetch_assoc())
$userid = $user;
because mysqli::fetch_assoc() with retrieve an associative array. Thus you have to access it like so (given the column name in your select):
$userid = $user["user_id"];

Msqli query array

So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Get all favorites for current user

I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.
$username = $this->session->userdata('username');
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"');
$rq = mysql_fetch_assoc($uidq);
$user_id = $rq['user_id'];
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user
And I don't know what to use next... I want to have something like:
foreach($favsr['bookmarked_song_id'] as $song_id) {
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_assoc($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.
It should be this:
$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
$songid = $row['bookmarked_song_id'];
...
}
mysql_fetch_array only loads one row,
it should be like that
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
while $favsr = mysql_fetch_array($getfavq);
{$songid=$favsr['bookmarked_song_id'];
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_array($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:
$username = $this->session->userdata('username');
//Select your user
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->limit(1);
$user_query = $this->db->get('users');
if($user_query->num_rows() > 0)
{
// We found a user
$user = $user_query->row(); // select a single row
// Grab this user's favorites
$this->db->where('user_id', $user->id);
$favorites_query = $this->db->get('favorites');
$songs = $favorites_query->result();
if($songs)
{
foreach($songs as $song)
{
$song_id = $song->bookmarked_song_id;
$tag = $song->bookmark_tag;
// Do stuff with data.
}
}
else
{
// No songs/favorites found, catch error
}
}
else
{
// No such user found, catch error
}
Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.

Making a function to query the Database

I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ID'";
$s = mysql_query($q);
$r = mysql_fetch_array($s);
}
But when I try and use it it will not access the row the way I want it to.
$user = '999';
connectUser($user)
echo $r['name'];
But if I put echo $r['name']; in the function it will work.
your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);
thare are 2 major problems in your code
the function doesn't return anything and you don't assign it's result to a variable.
Your variables doesn't match. $ip doesn't seem the same variable with $ID
so, this one would work
function connectUser($id) {
$q = "SELECT * FROM users where ID=".intval($id);
$s = mysql_query($q);
return mysql_fetch_array($s);
}
$user = '999';
$r = connectUser($user)
echo $r['name'];
That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ip'";
$s = mysql_query($q);
return mysql_fetch_array($s);
}
And then outside have:
$user = '999';
$r = connectUser($user)
echo $r['name'];
You might also want to take a look at this question: prepared statements - are they necessary
This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)
Please understand what is variable scope first,
and the function
A workable example, can be like :-
function connectUser($db, $ip)
{
$q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
$s = mysql_query($q, $db); // should have error checking
return mysql_fetch_array($s); // value to be returned
}
How to use :-
$db = mysql_connect(...);
$res = connectUser($db, "some value");

Categories