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"},';
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);
}
}
this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe
I am trying to bring mysql data into jquery by using php, I get the data into a JSON format like this.
{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}
using this following code:
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}
I am using jquery .get to pull it into the web page with this code.
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});
It displays the json data as above. I would like to be able to access the different elements individually, how do I do that?
If you wrap it with <script> tags, and declare it as a variable, you will have it.
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
echo "<script>";
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo "var myJson=" . $data;
}
echo "</script>";
Now in your main page scripts, you can access this JSON like any other normal JSON.
Here is an interval that you can place anywhere in your main page scripts:
It is just to test this ;)
var checkJson = setInterval(function(){
if(typeof(myJson.uid)!="undefined"){
clearInterval(checkJson);
console.log("myJson uid: " + myJson.uid);
console.log("myJson title: " + myJson.title);
// etc...
}else{
console.log("JSON not loaded yet.");
}
},500);
Retrieve the json data to use json response jquery parse function. json data using this function
jQuery.parseJSON()
http://api.jquery.com/jquery.parsejson/
In your jQuery, add JSON.parse() before you append (data).
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(JSON.parse(data));
});
});
I just changed this line:
$("#display").append(JSON.parse(data));
Hope this helps!
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
I'm trying to use php to run a sql select statement to pull data from a database and then only output one column(username) to an array that I can then use to filter using a JS script. Similar to how facebook/twitter does their real time searching of contacts when you start typing someone's name in. I keep getting an error though in php when I try to pull the username column and set it to an array and output that:
<?php
session_start();
include_once 'dbconnect.php';
$contact = mysql_real_escape_string($con, $_POST['contact']);
$sql = "select * from users";
$result = $con->query($sql);
if ($result->num_rows > 0) {
($row = $result->fetch_assoc()) {
printf($row["username"]);
}
} else {
echo "0 results";
}
?>
It would help to know what the exact error PHP is giving you is. But from a cursory look on your code I believe you are missing a while keyword.
while ($row = $result->fetch_assoc()) {
printf($row["username"]);
}