Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}
Related
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
}
i try this
<?php
include 'koneksi.php';
$idbarang = $_GET['id'];
if($idbarang == !null){
$query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");
$result = array();
$i= 0;
while($row = mysqli_fetch_array($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
} else {
$query = mysqli_query($conn, "SELECT * FROM data_barang");
$result = array();
$i= 0;
while($row = mysqli_fetch_assoc($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
}
?>
and this the result
[
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
},
{
"idbarang": "ID-96037284",
"namabarang": "Sampoerna",
"jenisbarang": "Rokok",
"hargabarang": "12000"
}
]
I think you are asking why you are always going through the ELSE and never the IF. Thats because of this IF test
if($idbarang == !null){
Instead try
<?php
include 'koneksi.php';
if(!empty($_GET['id'])){
$idbarang = $_GET['id'];
You could also simplify that code quite a lot, and protect it from SQL Injection.
// Do the renaming of column names as part of the query
$sql = 'SELECT id_barang as idbarang, nama_barang as namabarang,
jenis_barang as jenisberang, jenis_barang as hargabarang
FROM data_barang';
if(!empty($_GET['id'])){
// add the WHERE clause on to the base query
$sql .= ' WHERE id_barang = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$res = $stmt->get_result();
} else {
$res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);
I am new to php and am trying to return a json response in a particular structure. Here is what I have tried so far:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
The code above returns this response:
However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:
And Here is how my database looks like:
How can I achieve this?
You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output
[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....
I have two tables one is country based and other is city based.
I tried
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
}
}else{
echo '{"response": '.json_encode($response).' "success": false}';
}
?>
currently my response showing
{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}
For detail code explanation check the inline comments
Modify the SQL query with related column names
The memory you have to take care. By default memory limit in php is 128MB in 5.3
Check the code and let me know the result
<?php
$data = array();
//include your database configuration files
include_once("config.inc.php");
//execute the join query to fetch the result
$sql = "SELECT country.country_id, country.name AS country_name,".
" city.city_id, city.name AS city_name FROM country ".
" JOIN city ON city.country_id=country.country_id ".
" ORDER BY country.country_id ";
//execute query
$sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query');
//check the number of rows count
if(mysqli_num_rows($sqlQuery) > 0 ){
//country id temprory array
$country_id = array();
//loop each result
while($result = mysqli_fetch_assoc($sqlQuery)){
//check the country id is already exist the only push the city entries
if(!in_array($result['country_id'],$country_id)) {
//if the city is for new country then add it to the main container
if(isset($entry) && !empty($entry)) {
array_push($data, $entry);
}
//create entry array
$entry = array();
$entry['Id'] = $result['country_id'];
$entry['name'] = $result['country_name'];
$entry['Cities'] = array();
//create cities array
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
//append city entry
array_push($entry['Cities'], $city);
$country_id[] = $result['country_id'];
}
else {
//create and append city entry only
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
array_push($entry['Cities'], $city);
}
}
}
//display and check the expected results
echo json_encode($data);
use like this
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo json_encode(array('result'=>'true','Cities'=>$mainArray));
}
}else{
echo json_encode(array('result'=>'false','Cities'=>$response));
}
?>
You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.
try {
$results = array();
$query = "SELECT * FROM country";
$values = array();
$stmt = $datab->prepare($query);
$stmt->execute($values);
while($country = $stmt->fetch(PDO::FETCH_ASSOC)){
$cities = null;
$query2 = "SELECT * FROM city WHERE country_id = ?" ;
$values2 = array($country['id']);
$stmt2 = $datab->prepare($query2);
$stmt2->execute($values2);
$cities = $stmt2->fetchAll();
if($cities){
$country['cities'] = $cities;
} else {
$country['cities'] = '';
}
array_push($results, $country);
}
echo json_encode(array("Countries" => $results));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>
I would appreciate it if anyone willing to tell how to echoing /print.
Below is the process of entering data into the database, before inserting it how can I echoing it to the table?
<?php
session_start();
if(isset($_POST['submit']))
{
include('class/stock_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
?>
Insert this:
echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";
Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.