I'm using php to fetch a db query that I want to make a table from. I want to put the query results into a json object and then use javascript from there to output the results into a table. I used json_encode to create the json object in php.
I'm fairly new to javascript so I'm a little confused as to how I can send the json object I've created to javascript and then output the results using javascript? Should I include the javascript in the same file as the php page or a different one?
If you can explain what you're doing that would be awesome because I really want to know what's going on at each step.
Here's what I have so far:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
Update:
So I went ahead and made xyz.php my backend page and made a main.php for displaying the results. I started off with this sample function to make sure my jquery was fetching the results from the xyz.php page. Now, I don't know how to display the results in a table using jquery.
Here's what I did for my main.php page:
<?php
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("xyz.php");
});
});
</script>
<div id="div1"></div>
<button>Show JSON Results</button>
What you can do is:
Make the PHP file as backend. So that,
xyz.php:
// PUT YOUR CODE HERE
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
AND it should be accessible from the URL.
For example: xyz.php?id=2000
Now, on the page from where you want to populate this data, use jQuery
$.post
And manipulate this json.
This will ensure your page loads faster as dynamic data is getting populated after initial page load.
Hope it works for you.
Related
Beginner coder struggling with what I'm guessing is a fairly simple problem. I have a webpage with a dropdown menu showing options built off of a javascript array. The current set is a static list of options:
var countries = ["Afghanistan","Albania","Algeria"];
autocomplete(document.getElementById("myInput"), countries);
I'm trying to replace that static list with values pulled from a table I have set up in a MySQL database. I'm able to pull in the values, but am having issues with the output being formatted correctly on the webpage.
Here's my SQL (which seems to be working fine):
<?php
$servername = 'localhost';
$username = 'root';
$password = 'password';
$dbname = 'coins';
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT name FROM uscoins";
$result = $conn->query($sql);
$testarray = array();
while($row = mysqli_fetch_array($result)){ // cycle through each record returned
$testarray[] = "\"".$row['name']."\""; // get the username field and add to the array above with surrounding quotes
}
$name_string = implode(",", $testarray); // implode the array to "stick together" all the usernames with a comma inbetween each
$conn->close();
?>
I updated the javascript to pull in values from the SQL query:
var countries = [<?php echo json_encode($name_string); ?>];
autocomplete(document.getElementById("myInput"), countries);
But instead of returning the array values in separate rows within the dropdown menu on the webpage, it returns them all as a single text string.
So instead of this
it looks like this
Is there something else I need to do to put the SQL output in the correct format for the javascript to process it in the same way as the static list?
Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.
I have such a request: I have to do JS script, that works with PHP script.
Right now i have such a PHP code:
~~~~~~ PHP ~~~~~~
<?php
$email = filter_input(INPUT_POST, 'email');
if (!empty($email)){
$host = "localhost";
$dbusername ="root";
$dbpassword ="";
$dbname = "email";
$conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
if (mysqli_connect_error()){
die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else{
$sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
if ($conn->query($sql)){
echo "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
else{
echo "<script type='text/javascript'>alert(\"Your email is already in our subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
$conn->close();
}}else{
echo "<script type='text/javascript'>alert(\"Don't forget to include your email address !\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
?>
And here is a challenge. Instead of currently js scripts in php (that they activate on clean page without any content) JS script has to work on page, without reload - on the same page, when the request was sent from. I don't know how to do that ( i'm quite new to JS ) and i hope for your hints
Thanks for advices
If you don't want to reload the rendered page, you will have to work the other way around: not PHP is generating the whole page, but a JS script is pulling information from a PHP script and uses this information to display the according note.
There are multiple ways to fetch information from a server using JavaScript, the most prominent being AJAX to load HTML chunks or JSON responses. Please search for those topics as this is a relatively broad topic and your question is much too broad as it is.
I have a working javascript webapp on my server, which allows us to load our research images, tag them and then save them with tagging metadata. We use php and mysql to save each session to our employee's accounts.
We wish to use PhoneGap to utilize iOS and Android devices running the same app on a portable device in the field. Rather than save locally we still want to utilize the remote storing of image/metadata on the same online database.
My question is, how to restructure our php/mysql calls to allow for this?
Currently our server based app uses a 'connect.php' file to access the db, then a series of .php files to perform various functions as called by the javascript.
ie: load.php, save.php, signing.php, imageUpload.php, etc.
Here's the connect.php code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
And here is a save.php file we call from the javascript:
<?php
require 'connect.php';
session_start();
if(isset($_REQUEST["jsonString"]) && isset($_REQUEST["user"])){
$user = $_REQUEST["user"];
$jsonString = $_REQUEST["jsonString"];
}
if (isset($_SESSION['user']) && $_SESSION['user'] == $user) {
//$sql = "INSERT INTO savetable (user, savestring) VALUES ('Doe', '".$jsonString."')";
$sql = "UPDATE savetable SET `savestring` = '$jsonString' WHERE `user` ='$user'";
if ($conn->query($sql) === TRUE) {
echo "This data saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}else{
echo "Please login.";
}
require 'disconnect.php';
?>
I'm able to run all functions of the app from a device using phonegap, but am hung up when it come to calling the php files to access the remote server.
Thank you
I am suing autocomplete to display values from database.
The file is as follows:
autocomplete.php
<?php
require_once "../includes/conf.php";
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
//$mysqli=mysql_connect('localhost','root','','autofield') or die("Database Error");
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['vName']." </n>".$row['id'];
}
}
?>
The above file retuens the name that will be displayed in the text filed. Along with that I would like to pass id as hidden field so that I can process the data in php
How should I go about it?
You can make use of input type hidden for this purpose.
<input type="hidden" value=".$row['id']."/>
try this:
$array = array();
while($row=mysql_fetch_array($result))
{
array_push($array ,array("value"=>$row['id'],"label"=>$row['vName']));
}
and in jquery code:
terms.push( ui.item.label );
$( "#hidtextboxid" ).val( ui.item.value);
make sure you create one hidden field in your code.
check this:
how to pass hidden id using json in jquery ui autocomplete?
i dont want to answer your question with mysql_query for two reasons:
1. mysql_query official status is Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
2. it is vulnerable to SQL injection, see How can I prevent SQL injection in PHP?
use PDO (PHP Data Objects ) instead, it is secured and it is object-oriented
here are some tutorials to master this in 12 videos http://www.youtube.com/watch?v=XQjKkNiByCk
replace your MySQL instance with this
// instance of pdo
$config['db'] = array
(
'host' => '',
'username' => '',
'password' => '',
'dbname' => ''
);
$dbh = new PDO('mysql:host=' . $config['db']['host'] .
';dbname=' . $config['db']['dbname'],
$config['db']['username'],
$config['db']['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
global $dbh;
//dbh is just a custom name for the object you can name it database
edit the credentials, next lets query your code, if the instance is not on the same file ie the connection script is being included then call upon global $dbh; before you start your sql so you bring the object to the current file otherwise
so your code will look like this
<?php
global $dbh;
//lets prepare the statement using : to input what ever variables we need to (securely)
$displayData= $dbh->prepare("SELECT vName,id FROM employee WHERE vName LIKE :my_data ORDER BY vName");
$displayData->bindValue(':my_data', $my_data , PDO::PARAM_STR);
//then we execute the code
$displayData->execute();
//store the result in array
$result = $displayData->fetchAll();
print_r($result); //take a look at the structured
//depending on the structure echoing could be like **echo $result[0][theIdYouTrynaGet];**
?>
And how would I retrieve it in the other page then?
<html>
<?php
include_once '/*the path of your file where the above is happening*/';
<input type="hidden" value="<?php echo $result['pass in your parameters'] ?>"/>
?>
<html>