MySQL output pulled into Javascript array results in ugly mess - javascript

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?

Related

How to echo and retrive multiple rows with php

First off all hello to you all. The problem is I am making an ajax call from javascript to php file. And in that php file there is a prepared statement which returns 15 rows. I need to json_encode() these rows and send back to the javascript file so that I can use all of these information in each row which are info about users' profile. What's wrong with my code? I call fetch_assoc() constantly until all of the rows are processed yet when I display it on the console it only shows one row.
This is get_info.php:
// Get the profile info
$stmt = $conn->prepare("SELECT teachers.fname, teachers.lname, profile.img_url, profile.gender, profile.introduction, profile.city, profile.preference, profile.keyword FROM profile INNER JOIN teachers ON profile.user_id = teachers.id WHERE profile.keyword=? ORDER BY RAND() LIMIT 15");
$stmt->bind_param("s", $keyword);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$resultArray = [];
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$resultArray = $row;
}
$result = json_encode($resultArray);
echo $result;
}
And this is the javascript file where the ajax request is:
$(document).ready(function()
{
$.getJSON("get_info.php", function(result)
{
console.log(result);
}
)})
You keep overwriting $resultArray every time you loop, so you'll only ever see the last row returned by the query.
You need to make assign $row to a new element of $resultArray each time you loop - then adds rows to the array, instead of overwriting the variable with a single row.
It's very simple to do that:
$resultArray[] = $row;
You may also want to read https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying to refresh your memory of this key bit of PHP syntax.

Php script to fetch database value in array to see in Drop down list

I want to display a drop-down list which pull out database values. My actual code working fine, but here I have to provide the list in the array itself. What i required is, without editing the code, i needed to pull out values from database to this array("state1","state2"....); which is equal to something like this array("$states");
$sql = "SELECT * FROM `States`";
$result = $conn->query($sql);
$i=0;
while($row = $result->fetch_assoc()) {
$t=$row['statename'];
$t[$i]=$row['statenname'];
$i++;
}
$countryArr = array( "INDIA" => array("$t"));
I tried the above code but its listing only one value from database.
Remove this line
$t=$row['statename'];
just keep it to be
$t[$i]=$row['statenname'];

use json and javascript to populate a table

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.

Dynamically insert new row using javascript, but how to save these multiple row in php/mysql

I have create multiple row by using javascript. Now how to save these row in mysql. I already using some type of code, its not working. here my code is
[http://jsfiddle.net/bb2pJ/]
and php code for adding these value.
`
include "config.php";
if(isset($_POST['submit']))
{
foreach ($_POST['code1'] as $key => $value)
{
$code1 = $_POST["code1"][$key];
$product1 = $_POST["product_name1"][$key];
$qty = $_POST["quantity1"][$key];
$rate = $_POST["amount_name1"][$key];
$total = $_POST["total_name1"][$key];
$sql = mysql_query("insert into testing(code,product,qty,rate,total)values('$code1','$product1','$qty1','$rate1','$total1')")or die(mysql_error());
}
}
?>`
From you Js fiddle code, you are trying to post array of values for each field (ie code, proddname, ...).
How are submitting these values? If not passing through ajax post, then you need to declare fields names like code[], product_name[] ... as array for all fields so they will be submitted as array.
Rest code you have writtten above should work by using proper field name like code for code[] ... .
Please put proper spacing between your keywords and values/fieldname in your insert into.. statement.

Pass hidden value from database when Using autocomplete feature

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>

Categories