Function Return Array PHP - php

I am trying to create a function that gets the name and clientid. What is the proper way to return an array? so that I can have multiple values returned.
function get_client_name($conn, $clientid){
$response = array();
$query = "SELECT NAME, CLIENTID FROM LCCLIENT WHERE CLIENTID = '". $clientid ."'";
$sql = oci_parse($conn, $query);
$exec = oci_execute($sql);
if($exec){
$row = oci_fetch_array($sql);
$response[] = array(
'CLIENTID' => trim($row['CLIENTID']),
'NAME' => trim($row['NAME'])
);
}
return json_encode($response);
}
echo get_client_name($conn, '2000000800')[0]['CLIENTID'];
echo get_client_name($conn, '2000000800')[0]['NAME'];

You just return your array, without encoding it in JSON format. Also don't call this function two times, because it's redundant to call DB two times for the same data. Second thing, you shouldn't pass $conn in this function. You should develop some structure for database connections.
function get_client_name($conn, $clientid)
{
$response = array();
$query = "SELECT NAME, CLIENTID FROM LCCLIENT WHERE CLIENTID = '" . $clientid . "'";
$sql = oci_parse($conn, $query);
$exec = oci_execute($sql);
if ($exec) {
$row = oci_fetch_array($sql);
$response[] = array(
'CLIENTID' => trim($row['CLIENTID']),
'NAME' => trim($row['NAME'])
);
}
return $response;
}
$clientName = get_client_name($conn, '2000000800');
echo $clientName[0]['CLIENTID'];
echo $clientName[0]['NAME'];

Related

How can i get all of my users from sql datebase with using php [duplicate]

This question already has answers here:
mysqli_fetch_array returning only one result
(3 answers)
Closed 3 years ago.
In $result should be all of users from datebase, but it takes only first person and shows error.
My php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'connect.php';
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = array();
$result['osoby'] = array();
$row = mysqli_fetch_assoc($response);
$index['name'] = $row['imie'];
$index['surname'] = $row['nazwisko'];
array_push($result['osoby'], $index);
$result['success'] = "1";
echo json_encode($result);
}
Its giving you 1 record because you are only printing 1 record,
Using $row = mysqli_fetch_assoc($response); will always give you last row if you not use loop here.
You need to use while loop to get all rows like:
<?php
$i = 0;
$result = array(); // initialize
while($row = mysqli_fetch_assoc($response)){
$result[$i]['name'] = $row['imie'];
$result[$i]['surname'] = $row['nazwisko']; // store in an array
$i++;
}
$finalResult['osoby'] = $result; // storing as you need
$finalResult['success'] = "1"; // no idea about this but adding this also
echo json_encode($finalResult); // encode with json
?>
You can loop the result-set and append an array of your values to the $result array.
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => []];
while ($row = mysqli_fetch_assoc($response)) {
$result['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
$result['success'] = "1";
echo json_encode($result);
If you have the mysqlnd driver installed, you can also use mysqli_result::fetch_all() method
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => mysqli_fetch_all($response, MYSQLI_ASSOC)];
$result['success'] = "1";
echo json_encode($result);
You have to loop the result array.
$resultJson = array();
$resultJson['osoby']=array()
$query = "SELECT imie,nazwisko FROM users";
$result = $mysql->query( $query );
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
// fetch information out of the $row..
$resultJson['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
}
print json_encode($resultJson);

Outputting concatenated data from mysql to json as json object

This is my database:
Am trying to get all from_id which to_id is 4 to a json object where ill be able to show all messages from a from_id in a stack sorted by their different time_sent
I have tried:
CODE:
DATABASE QUERY CLASS(THIS IS IN THE DBASE CLASS)
public function query($sql){
$this->_last_query = $sql;
$result = mysqli_query($this->_conndb, $sql);
$this->displayQuery($result);
return $result;
} // end of query
public function displayQuery($result){
if(!$result){
$output = "database query failed :". mysqli_error($this->_conndb);
$output .= "last sql query was: ".$this->_last_query;
die($output);
}
else{
$this->_affected_rows = mysqli_affected_rows($this->_conndb);
}
} //End of query results
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
while($row = mysqli_fetch_assoc($result)){
$out[] = $row;
}
mysqli_free_result($result);
return $out;
}
MESSAGE CLASS:
private $_table = 'messages';
public function getadminMessage(){
$sql = "SELECT group_concat(messg, time_sent, from_id) as from_id from {$this->_table} where to_id = 4 group by from_id";
return $this->db->fetchAll($sql);//IN THE DBASE CLASS ABOVE
}
In the file getadminmessage.php
$message = new Message();
$results = $message-> getadminMessage();
echo json_encode($results);
I then use getjson
$.getJSON("http://127.0.0.1/tum_old/custom/php/getadminmsg.php",
function(response){
console.log(response);
});
On my log i get
The data seems group concatenated but i would also like the various messages to be in object form that is the messages to be displayed as objects such that i can easily do:
data.object[0].from_id[0].msg to get TRUE LOVE as the message
scais::::
for select you need
$sql = "SELECT group_concat(messg) as msg, time_sent, from_id
from {$this->_table} where to_id = 4 group by from_id";
for server side you need json_encode the array
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
$cnt =0;
while($row = mysqli_fetch_assoc($result)){
$out[$cnt]['msg'] = $row['msg'];
$out[$cnt]['time_sent'] = $row['time_sent'];
$out[$cnt]['from_id'] = $row['from_id'];
$cnt++;
}
mysqli_free_result($result);
return json_encode($out);
}
Try this:
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
while($row = mysqli_fetch_assoc($result)){
$out[] = array(
'id' => $row['id'],
'from_id' => $row['from_id'],
'to_id' => $row['to_id'],
'msg' => $row['messg']
);
}
mysqli_free_result($result);
return json_encode($out);
}
Try removing the group by statement and building a new multi dimensional array instead with the result rows before you output it as a json encoded string. See example below
$out = array(
'messages' => array(),
);
while($row = mysqli_fetch_assoc($result)){
$out['messages'][$b['from_id']][] = array(
'msg' => $b['message'],
'time_sent' => $b['time_sent'],
);
}
return $out;
The keys in your $out['messages'] array will be your from_id values. Each entry will be arrays of messages from each id, so in your javascript you should be able to iterate over these

My php file does not return all values in JSON form

So I have a database and I have written a php file that inserts value to the table and then returns all the values in this table.
However, my code only returns just one random value from the table and not all of them. I am not sure why, but this is my code:
<?php
include_once "init.php";
if(!empty($_POST['names'])){
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names)
VALUES('NULL', ?)";
$results = $conn -> prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
echo json_encode("Success");
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
$response = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
echo json_encode($response);
}
else{
echo json_encode("Something went wrong");
}
?>
EDIT: Thank you guys for providing me a solution so quickly! I fixed it and it works but the first echo json_encode("Success"); is not being executed.
In your line here:
$response["names"] = $row["names"];
You are replacing the value of $response["names"]. Instead, try adding it to an array:
$response = array("names" => array());
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
To use one JSON object, you'd initialize $response at the top and change the values as needed.
<?php
include_once "init.php";
$response = ['success' => false, 'message' => null, 'names' => []];
if(empty($_POST['names'])) {
$response['message'] = 'No names were provided in the request';
} else {
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names) VALUES('NULL', ?)";
$results = $conn->prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
$response['success'] = true;
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response['names'][] = $row['names'];
}
}
}
echo json_encode($response);

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

How to read "fetch(PDO::FETCH_ASSOC);"

I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.
For example, let’s say that I have this code:
$sql = "SELECT * FROM users WHERE user_id = :user_id";
$stmt = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.
How does this work?
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => 'youremail#yourhost.com'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
Loop through the array like any other associative array:
while($data = $datas->fetch(PDO::FETCH_ASSOC)){
print $data['title'] . '<br>';
}
or
$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
echo '<pre>' . $resultset . '</pre>';
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.
You can access the name field like this: $user['name'].
I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name
To read the result you can read it like a simple PHP array.
For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return one tuple though. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.
Design Pattern "table-data gateway"
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
Print all row with column 'user_id' only
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
Print user_id = 1 with all column
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
Print user_id = 1 with column 'email and password'
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];
consider the following code script, will help.
$stm = $accountdb->query($sql);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
$number = $stm->rowCount();
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
header("Content-type: application/json");
echo '{"total" : "' . $number . '","records" : ' . $json . '}';

Categories