Why is this piece of code giving me duplicate results? - php

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);
}
}
}
?>

Related

How to make json like this from database mysql using php

{
"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);

How to get value from mssql DB in PHP

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);
}
}
}

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

PDO Search Engine?

I created a search feature for my website prior to me rewriting in PDO. I'm incredibly new to both PHP and PDO for use with a MySQL database, and I cannot for the life of me figure out how to translate this code, to PDO. I would appreciate someone talking me through it slightly, to help me learn.
My current code is:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'";
$query = mysqli_query($connect, $sql);
$count = mysqli_num_rows($query);
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = mysqli_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
A PDO connection has been made, and it appears to be successful. This is in my functions.php file, and my connection.php file has been attached to functions.php.
Thanks in advance!
It should be something like
$conn='';
try {
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
}
catch (PDOException $e) {
exit('Database error.');
}
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}

How to convert mysqli_fetch_assoc results into json format?

i am trying to convert the result of my query into a json format so i can grap it with jquery in another file. I dont get any errors but its not recognised as json.
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result[] = array('patient'=>array('id' => $dbloginID, 'name' => $dbname));
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);
please try this:
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
$result = array();
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result['patient'][] = array('id' => $dbloginID, 'name' => $dbname);
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);
You should declare $result outside while loop like this
$result = array();

Categories