Get data from a mysql database to use in jquery-ui autocomplete - php

I have an input form and I need to populate the autocomplete with data from a database. My approach seems to be working BUT I am pretty sure it's not the most efricient way. (I'm new to php, javascript)
Here's my code:
//get all organizations
$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row) {
$sql = "SELECT id, name FROM organizations WHERE id = :id";
$stmt = $pdo->prepare($sql);
$id = $row['id'];
$stmt->bindValue(':id', $id);
$stmt->execute();
$org_id = $stmt->fetch(PDO::FETCH_ASSOC);
//echo $org_id['name'];
$org_array = $org_array . '"' . $org_id['name'] . '",';
}
}
And here is the JS part:
<input type="text" class="form-control autocompleteOrgs" name="newOrganization" id="newOrganization" aria-describedby="newOrganizationHelp" value="<?php echo
$my_profile['organization']; ?>">
<script>
$(function() {
var orgTags = [<?php echo $org_array ?>];
$(".autocompleteOrgs").autocomplete({
source: orgTags
});
});
</script>

You don't need to fetch organizations one more time, better approach would be:
$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
$org_array = implode(',', array_column($results, 'name'));
}

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

Why does the function of two database queries show me only the result of the first query?

The output of the following shows me the result of the first query, but not the second. When I make the queries without function it works.
function builtFooter($catactive, $catlink)
{
global $conn;
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>' . $cat['name'] . '</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$result = $stmt->get_result();
while ($city = $result->fetch_assoc()) {
$resArr[] = $city;
echo ' ' . $city['city'] . ' <br />';
}
}
}
builtFooter('yes', 'markt');
This queries are working fine, and I get the result I want:
$catactive = 'yes';
$catlink = 'markt';
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>'.$cat['name'].'</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$r = $stmt->get_result();
while ($city = $r->fetch_assoc()) {
$resArr[] = $city;
echo' '.$city['city'].' <br />';
}
}
But when I built a function, I do not get the results of the secode query:
function builtFooter($catactive,$catlink){
global $conn;
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>'.$cat['name'].'</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$r = $stmt->get_result();
while ($city = $r->fetch_assoc()) {
$resArr[] = $city;
echo' '.$city['city'].' <br />';
}
}
}
builtFooter('yes','markt');
I have the tables categories, ads, neueorte. I want built footer links, so I want the categorie as a h3 tag and the cities grouped by city where ads are placed. I hope I made it right, I am new to this page.

Why is this piece of code giving me duplicate results?

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

How to Merge PDO Mysql Array Data using Php

I need to merge categories and subcategories into one array. Here is code.
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_push($cat, $list);
echo $data;
}
I am getting 2 value when printing instead ids numbers
are you want to merge $cat and $list?
you can try:
array_merge($cat, $list);
I solved this problem with the help of this post combine-results-from-two-pdo-queries
$id = '1';
$results = array();
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $rows['id'];
}
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $id);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $row['id'];
}
var_dump($results);
I think what you want is this:
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
$data = array();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_merge($data, $cat, $list);
//$data = array_unique($data);
print_r($data);
}
Notice the $data = array(); before the while loop. With array_merge you merge categories and subcategories with the $data array into the data array.
If you happen to get duplicted value you do not need or want, simply uncomment $data = array_unique($data); and it will erase duplicated entries for you.
Please clarify your question, if I do not address your problem and I will update my answer.
Have fun, may the source be with you.

JSON parse Mysql query result in php pdo

I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above

Categories