I have two rows contaning data of same id.
It has different adresses in different rows for the same id.
I want to fetch both the adress in different variable in php.
How can i do this? Please help!
Below is the code:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
It gives me both the address of the same id in one variable only.
I want them in two different variables.
You are already getting an array of addresses in $d.
What you can do is:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
If you have address ids 2 and 4, you will get two variables
$ad_2 and $ad_4
You should use parameterized queries. Use PHP's PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Don't want your queries getting injected with attacks.
I suggest you to use mysqli instead.
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
and then
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
you can verify it:
print_r($data);
Related
I am trying to display a nested json as seen in this picture
JSON Ouput
However it only gets the last data. I am sure that the 1st id has a data. Please see the code below
<?php
include 'conn2.php';
$pdo = new PDO($dsn, $user, $passwd);
$stmt = $pdo->prepare("CALL sp_foods_display();");
$stmt->execute();
$stmt->bindColumn('bar_name',$bar_name);
$stmt->bindColumn('address',$address);
$stmt->bindColumn('id',$post_id);
$response = array();
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp["bar_name"] = $bar_name;
$temp["address"] = $address;
$temp["item_details"] = getItem($post_id);
array_push($result, $temp);
}
$response["result"] = $result;
echo "<pre>" . json_encode($response,JSON_PRETTY_PRINT) . "</pre>";
function getItem($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM fct_menu_foods WHERE post_id = :cur_post_id ORDER BY id ASC");
$stmt->bindParam(":cur_post_id",$id,PDO::PARAM_INT);
$stmt->execute();
$food_details = array();
$stmt->bindColumn('food_name',$food_name);
$stmt->bindColumn('price',$price);
$stmt->bindColumn('img_name',$img_name);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp = array();
$temp["food_name"] = $food_name;
$temp["price"] = $price;
$temp["img_name"] = $img_name;
array_push($food_details, $temp);
}
return $food_details;
}
?>
my target output is to display all data in nested.
I found a solution. My bad. You have to closeCursor(); for every query and use fetchAll for getting the data.
I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);
i have a trouble, when select table user in yii2 , data no show up
$sqlGetuser = "select * from user ";
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
foreach($sqlquery as $row){
// echo $row;
// echo "saya";
echo $row['username'];
}
The error is in this line:
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
query() returns yii\db\DataReader. To return array of rows use queryAll():
$rows = Yii::$app->db->createCommand($sqlGetuser)->queryAll();
If you want to use query(), you need to read data differently:
$command = $connection->createCommand('SELECT * FROM "user"');
$reader = $command->query();
while ($row = $reader->read()) {
$rows[] = $row;
}
// equivalent to:
foreach ($reader as $row) {
$rows[] = $row;
}
// equivalent to:
$rows = $reader->readAll();
See more in official docs.
Also quote table name as adviced since it's reserved word.
So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function