I'm using the autocomplete UI for my search box. Below is my php code:
<?php
include 'connect.php';
if (isset($_GET['term'])) {
$value = $_GET['term'] . '%';
$return_arr = array();
$stmt = $conn->prepare("SELECT * FROM jobs WHERE jobname LIKE ? or formtype LIKE ?");
$stmt->bind_param("ss", $value, $value);
$stmt->execute();
$stmt->bind_result($entryid, $jobnumber, $jobname, $formtype, $date);
while ($stmt->fetch()) {
$return_arr[] = $jobname;
$return_arr[] = $formtype;
}
echo json_encode($return_arr);
}
?>
Everything works perfectly fine. But I kind of want for the while statement to return all $jobname values first before the $formtype values. In short, I want the values to be returned by column and not by row. I'm not sure how it is possible because I tried putting them inside do while and foreach statements but both didn't work for me.
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
. But I kind of want for the while statement to return all $jobname values first before the $formtype values.
Build two arrays and then merge them:
$ar1 = [];
$ar2 = [];
while($stmt->fetch()) {
$arr1[] = $jobname;
$arr2[] = $formtype;
}
$return_arr = array_merge($arr1, $arr2);
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
Because autocomplete expects json object and you want to try give him json object and something else
Related
I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
Basically I have a database and I'm making a webpage with PHP.
I get a row of Elements from my database and put them into an array.
I need to display this array in my webpage, and the elements out of it have to be ajax links that display more information.
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$id = $row["name"];
$echo "$id";
This is my array where i have a list of names and i print it there, i want my prints to be links.
Any help? I'm pretty desperate
Make the datatype of AJAX call as JSON in the javascript and return a json encoded string from php. Then in the success block of the AJAX call , parse it by JSON.parse()
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$categoryDetails[] = $row;
}
echo json_encode( $categoryDetails );
I'm working on a script that forms a web page based on what is in my database. For his I call a java script function when the page loads and whenever the page needs to update.
Firstly I made a script that gets the information from the database, passes it to java script by echo "var region_list = ". $js_region_list . ";\n"; and then proceeded to generate the page itself which worked.
After that I tried to get this to work based on an AJAX request but this failed horribly. As it stands I get correct information from the database but it does not change the value of echo "var region_list = ". $js_region_list . ";\n"; which prevents the page from updating.
The PHP part of my script:
if(isset($_POST["campaign_id"])){
// Get variables and sanetize
$campaign_id = preg_replace('#[^0-9]#i', '', $campaign_id);
// Create planet list
$planet_list = array();
$sql = "SELECT planet_nr, size, moon FROM planets WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($planet_list, array($row["planet_nr"],$row["size"],$row["moon"]));
}
/* free result set */
mysqli_free_result($result);
}
// Create region list
$region_list = array();
$sql = "SELECT planet_id, region_id, region_type, owner FROM regions WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($region_list, array($row["planet_id"],$row["region_id"],$row["region_type"],$row["owner"]));
}
/* free result set */
mysqli_free_result($result);
}
// Convert array's for use in java
$js_planet_list = json_encode($planet_list);
$js_region_list = json_encode($region_list);
$list = array($planet_list, $region_list);
$list = json_encode($list);
echo $list;
exit();
The javascript part:
<?php
echo "var planet_list = ". $js_planet_list . ";\n";
echo "var region_list = ". $js_region_list . ";\n";
?>
var ajax = ajaxObj("POST", "campaign.php?c="+campaign_id);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "Fail"){
alert(ajax.responseText);
}
}
}
ajax.send("campaign_id="+campaign_id);
NOTE: These are just snippets of the whole script. The whole script is in the same PHP file with the PHP up above between it's tags and the java down between the script tags.
In your ajax success part, you need to just update the values of the the variables planet_list and region_list as shown below
planet_list = JSON.parse(ajax.responseText[0]);
region_list = JSON.parse(ajax.responseText[1]);
Objective: We need that it find registered people and shows which countries had visited like In this image
We need to make a loop that creates php objects (The artists), with its own classes. This objetcs will come from a DataBase (mysql). For each of this objects, we need that it looks in the DataBase which rows are related with it (countries), and make it an php objetc too, with its own classes (Its own design with CSS, HTML)
We already tryed Angular with ng-bind-html so it could read HTML tags and its CSSs, but it only took the first loop, and the second one just didn't appeard. We tryed while inside another while, but I don't know what happens, but it only takes the first one.
The idea to make a loop this way is to hide countries while the user doesn't want to see them. If they click on the artist name, it will shows up the countries. But this is another story, we think we will use CSS for that.
I'll put the code I tryed to use for Angular, just in case someone have an idea with Angular.js.
Thank you very much for reading this. Best Wishes and Best Regards !
$data;
$data['info'] = "";
$id = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
}
$sql = "SELECT ....WHERE artist.artist_id = $i"; //This is to call only artist that the user actually have access to see.
$query = $connection->prepare($sql);
$query->execute();
while($row = $query->fetch()){
$artists[] = $row;
};
if (isset($artists)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
foreach($artists as $art) {
$a = $art['artist_id']
$data['info'] .= "<div class='Main'>
<div class='MainResult'>
{$art['artist_name']}
</div>
<div>
<div class='VisitedPlaces'>
<?php
$sql='SELECT country_name, country_city, country_time FROM country JOIN ...... WHERE... = $a';
$query = $connection->prepare($sql);
$query->execute();
// 2- Here's the second loop, that look for the countries related to the artist. The idea is that once it finish, look for the next artist in the first loop. This one don't works.
while($row = $query->fetch()){
$country = $row['country_name'];
$city = $row['country_city'];
$time = $row['country_time'];
echo '<div class="rslt">
<h2>'.$country.'</h2>
<span>'.$city.'</span>
<span>'.$time.'</span>
</div>';
};
?>
</div>
</div>";
}
echo JSON_encode($data);
}
It's not actually an answer, but some of my suggestions/advices.
First of all code logic is partially not understandable, some variables appears from nowhere. For example: $i and $artists.
Next one - why do you need to return an html-code instead of pure-data?
Third, subjective on me I guess, that the access to the mysql every time is a bad idea.
My vision looks like that:
notice: I haven't test this
<?php
$data = array();
$data['info'] = array(); // changes
$rol = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
die(); // added
}
// what data gets from database?.. idk
// it seems like companies .. what / why / where it used in this code ? unknown
// what is $i ? I guess - artist_id
$sql = "SELECT ....WHERE artist.artist_id = :artist_id";
$query = $connection->prepare($sql);
$query->bindParam(':artist_id', $i, \PDO::PARAM_INT); // suggestion
$query->execute();
$companies = $query->fetchAll(\PDO::FETCH_ASSOC);
// from where we have got this ?
if (isset($countries)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
$artist_ids = array();
// from where this too ? okay, just use it
foreach($artists as $art) {
$artist = array();
// it's just a suggestion about your table scheme
$artist_id = $art['artist_id'];
$artist_ids[] = $artist_id;
$artist['name'] = $art['artist_name'];
$artist['visited_places'] = array();
$data['info'][$artist_id] = $artist;
}
// here is not an actual sql-query, I suggest that country data and artists data are separated
// and sql must be modified to get data from both table at once
$sql = 'select country_name, country_city, country_time, artist_id from country join ... where ... and artist_id in ('.implode(',',$artist_ids).')';
$query = $connection->prepare($sql);
$query->execute();
// I don't know how many rows it will be
// make this safer, get row by row
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$artist_id = $row['artist_id']; // according the new query
$place = array();
$place['country'] = $row['country_name'];
$place['city'] = $row['country_city'];
$place['time'] = $row['country_time'];
$data['info'][$artist_id]['visited_places'][] = $place;
}
} // if $countries
// send back pure-data, your javascript can do anything
echo JSON_encode($data);
} // if $_POST['id']
after all your front-end javascript application will receive a JSON-string, something like this: {"info":{"110":{"name":"Michael Jackson","visited_places":[{"country_name":"JP","country_city":"Tokyo","country_time":"12-sep-1987"},{"country_name":"US","country_city":"New-York","country_time":"03-mar-1988"},{"country_name":"IT","country_city":"Rome","country_time":"23-may-1988"}]}}}
php source:
[info] => Array
(
[110] => Array
(
[name] => Michael Jackson
[visited_places] => Array
(
[0] => Array
(
[country_name] => JP
[country_city] => Tokyo
[country_time] => 12-sep-1987
)
[1] => Array
(
[country_name] => US
[country_city] => New-York
[country_time] => 03-mar-1988
)
[2] => Array
(
[country_name] => IT
[country_city] => Rome
[country_time] => 23-may-1988
)
)
)
)
)
I have this JavaScript code that is working well:
var lookup = {
"dog-black":{url:'images/dog-black.jpg'},
"dog-white":{url:'images/dog-white.jpg'},
"cat-black":{url:'images/cat-black.jpg'},
"cat-white":{url:'images/cat-white.jpg'}
};
I'm tring to generate same code dynamically using PHP to have lines as much as there in the DB, like this:
var lookup = {
<?php
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '"'.$row['name'].'":{url:images/'.$row['name'].'.jpg';
}
} else {echo "No records";}
?>
};
I tried to define the php code as string using quotes or heredoc and alert the string variable, but seems like the script is not excuted
note: i'm already connected to the DB before this part of code and pass data from/to it.
Don't try to echo this out manually. What you can do is build the same structure in PHP, then use json_encode.
JSON is actually valid JavaScript code, so it will work.
Try it like this:
<?php
$lookup = array();
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$lookup[$row['name']] = array('url' => 'images/'.$row['name'].'.jpg');
}
}
else {
//echo "No records";
}
?>
var lookup = <?=json_encode($lookup); ?>;
There seems to be a mistake in the echo in the while loop. You're not closing the string correctly, it is missing the closing part },. Which should look something like this:
echo '"'.$row['name'].'":{url:"images/'.$row['name'].'.jpg"},';