I am new in PHP and trying to build one API which provide me json response of required data. There one table called user and I need email, username and user_type from it. I have coded like below for do it
$result = array();
$users = getOnlineUsers($conn);
$userinfo['email'] = $users['email'];
$userinfo['username'] = $users['username'];
$userinfo['user_type'] = $users['user_type'];
$result['status'] ="success";
$result['userData'] = $userinfo;
And function is like below
function getOnlineUsers($conn)
{
$q = $conn->prepare("SELECT * FROM table_users WHERE online_status = 1");
// $q->bind_param("s", $email);
$q->execute();
$result = $q->store_result();
$metaResults = $q->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams='';
foreach($fields as $field){
if(empty($statementParams)){
$statementParams.="\$column['".$field->name."']";
}else{
$statementParams.=", \$column['".$field->name."']";
}
}
$statment="\$q->bind_result($statementParams);";
eval($statment);
$q->fetch();
return $column;
}
Its working fine but giving me only one row in response. I want get all row instead of one. I am getting response like this
{"status":"success","userData":{"email":"abc#gmail.com","username":"rajrathodbvn","user_type":0}}
Let me know if someone can help me for solve my issue.
Thanks
That's a lot of code for something so simple. Select the columns you want:
function getOnlineUsers($conn) {
$q = $conn->prepare("SELECT email, username, user_type
FROM table_users
WHERE online_status = 1");
$q->execute();
return $q->fetchAll(PDO::FETCH_ASSOC);
}
Then assign:
$result['status'] = 'success';
$result['userData'] = getOnlineUsers($conn);
Or:
$result = ['status' => 'success', 'userData' => getOnlineUsers($conn)];
Related
I am having issues retrieving the primary key from a table.
My table structure is as follows.
In the table is a single record:
id = 1
PlaceName = 'in the matrix'
Retrieved using the following SQL statement directly:
SELECT id
FROM rde_613949.dbo.PlaceNames
WHERE PlaceName = 'in the matrix';
I am attempting to retrieve the id of this record using the following method:
function GetPlaceNameId($locationName)
{
//returns the id of the location name, creating if required
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "SELECT id from rde_613949.dbo.PlaceNames where PlaceName = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query($resource, $tsql, array($locationName), $options);
if ($stmt)
{
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
{
$recordFound = true;
$locationId = $row['id'];
return $locationId;
}
}
else
{
return $this -> AddPlaceToDatabase($locationName);
}
}
This method fails at
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
$row returns as null, which means $location also returns as null.
I have another table with another method where this approach works. The only real difference is that I am not returning the primary key in the one that works.
public function FindStudentRecord($studentId)
{
require_once("./Student.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select FirstName, LastName from rde_613949.dbo.Students where StudentId = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$result = sqlsrv_query($resource, $tsql, array($studentId), $options);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$student = new Student($studentId, $row['FirstName'], $row['LastName']);
return $student;
}
return null; //no records found return null
}
Please can someone explain the difference in this situation to me and advise me how to do this correctly, please?
While I do not understand why I got around this by selecting * instead of selecting id. If anyone understands this please do a post to advise.
I am creating a function that is suppose to get the first name and last name from the database and return the query. Something is not right about it though.
The first and last names don't show up. I'm not getting any errors or warnings and I've tried all of the answers provided on this site and others(there is not much though).
Can someone tell me what is wrong with it ?
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
return $row;
}
First of all if you are trying to finding a better way you can use this one
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$result = $query_result->fetch_all(MYSQLI_ASSOC);
Return $result;
}
mysqli has a handy function that instantly returns an array from the query result: mysqli_fetch_all(). So instead of this lines
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
it could be just a single line:
$result = $query_result->fetch_all(MYSQLI_ASSOC);
if you are looking to finding the answer why your function will return null i will explain for you :
There is some mistake in your codes
first of all when you execute this line $query_result->fetch_array();
actually you just make empty the mysqli buffer! so you don't have anything in buffer to catch it in this line -> while ($row = $query_result->fetch_assoc()) {
and in other hand even if you had something in buffer then you dont do nothing in this line ->
$row['first_name'];
if you are looking to correct your codes you should write the code like this ->
first of all make comment this line -> $query_result->fetch_array();
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row['first_name'];
}
return $result;
}
Edit:
if you are looking to get both first name and last name you have to do like this ->
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row;
}
return $result;
}
Try with $query->bind_param(":username", $username)
and change in the query the ? by :respuesta
"SELECT first_name, last_name FROM users WHERE username = :username
Looks the docs and apologies for my poor english
https://www.php.net/manual/es/pdostatement.bindparam.php
I am new with php, I try to call the following function in order to populate an array of previously inserted data in mysql, but I get null.
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
$result_arr = array();
while($row = mysqli_fetch_array($res))
{
$result_arr[] = $row;
}
return $result_arr;
}
and then I try to construct my json object as..
$result_business = array();
$result_business = GetBusiness($con, $email);
$json['result'] = "Success";
$json['message'] = "Successfully registered the Business";
$json["uid"] = $result_business["id"];
$json["business"]["name"] = $result_business["name"];
$json["business"]["email"] = $result_business["email"];
but for even if the data are inserted successfully the part of $result_business is null, why I get null? I my $query typed wrong?
thank you
The problem is, your function GetBusiness returns a multi-dimensionnal array, you can use this one instead :
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
return mysqli_fetch_array($res);
}
Also, you must use the MySQL columns that you selected to access the data of the rowset. Something like
$json["uid"] = $result_business["B_ID"];
$json["business"]["name"] = $result_business["B_NAME"];
I'm currently trying to fetch two images location from my database, how do I return both columns and if both empty then echo another image. This is what I've got so far.
How do I return both photo and photo_small so that I may echo them in a php file.
PUBLIC FUNCTION Profile_Pic($uiD) {
$sth = $this->db->prepare("SELECT photo,photo_small FROM users WHERE uiD = :id");
$sth->execute(array(':id' => $uiD));
if ($sth->rowCount() > 0) {
$data = $row['photo'];
return $data;
} else {
$data = './icons/users.png';
return $data;
}
}
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo'])) {
$data['photo'] = './icons/users.png';
}
if (empty($data['photo_small'])) {
$data['photo_small'] = './icons/users.png';
}
return $data;
}
if you want to replace both images if even one is absent
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo']) || empty($data['photo_small'])) {
$data['photo'] = './icons/users.png';
$data['photo_small'] = './icons/users.png';
}
return $data;
}
Just return all of the values you want in an array.
You can ensure that both photo and photo_small are not empty strings or NULL by using empty().
Don't forget to retrieve your row using PDOStatement::fetch().
You should not use rowCount() to determine the number of rows returned in a SELECT statement. According to the documentation for PDOStatement::rowCount():
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Try this:
$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row && !empty($row['photo']) && !empty($row['photo_small'])) {
$data = array('photo' => $row['photo'], 'photo_small' => $row['photo_small']);
return $data;
} else {
$data = array('photo' => './icons/users.png', 'photo_small' => './icons/users.png');
return $data;
}
Then when you call the function, your returned result can be used like this:
$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];
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.