I'm a beginner in using PHP and Javascript, and I don't have any idea on how to store the data that I've gathered from MySQL which I placed in a multidimensional array in PHP to a 2D array in Javascript. Here's my working code in PHP:
<?php
function connecToDatabase(){
$host = "localhost";
$username = "root";
$password = "p#ssword";
$database = "flood_reports";
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
}
function retrieveData(){
connecToDatabase();
$data = mysql_query('SELECT * FROM entries') or die(mysql_error());
$entries = array();
$index = 0;
while($info = mysql_fetch_array( $data ))
{
$entries[$index] = array('entry_id' => $info['entry_id'],
'location' => $info['location'],
'image_dir' => $info['image_dir'],
'longitude' => $info['longitude'],
'latitude' => $info['latitude'],
'level' => $info['level']);
$index++;
}
$json = json_encode($entries);
echo $json;
mysql_close();
}
retrieveData();
?>
on the end of your script add the following
<script type="text/javascript">
var jsvar = <?php echo $phpvar;?>
</script>
Replace
echo $json;
with
echo 'var fromPhp = ' . $json . ';';
You just need to put the data into a variable. This will make it available as fromPhp on the browser side.
Related
I need to define my website var from mySQL, but I don't know how to get the data to the var. This is what I have so far.
I'm able to get the data in JSON with this:
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
I'm stuck in this part.
<?php
$connect = mysqli_connect("localhost", "user", "", "pricesdb");
$sql = "SELECT * FROM precios";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result)) ?>
<script type="text/javascript">
var websiteVars = {
priceusd: <?php echo ''.$row['priceusd'].''?>,
pricebs: <?php echo ''.$row['pricebs'].''?>
};
</script>
You're redefining the variable websiteVars each time through the loop.
You should keep the original loop that creates the array $json_array, and then encode the entire thing into the JavaScript variable;
var websiteVars = <?php echo json_encode($json_array); ?>;
Thank you very much, I was able to solve the problem this way.
<?php
$db = mysqli_connect("localhost", "root", "", "db");
$sql = "SELECT * FROM precios";
$result = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
?>
<script type="text/javascript">
var websiteVars = {priceUsd: <?php echo ''.$row['priceUsd'].''?>, priceBS: <?php echo ''.$row['priceBS'].''?>};
<?php
}
?>
</script>
I am retrieving contents from my database(MYSQL) in PHP. The following is my PHP script:
<?php
$username = "**";
$password = "**";
$host = "**";
$database="**";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT * FROM data1
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
The output is a perfectly formatted JSON Object:
[{"ID":"1","Country":"India","Value1":"100","Value2":"200"},{"ID":"2","Country":"India","Value1":"230","Value2":"800"},{"ID":"3","Country":"USA","Value1":"30","Value2":"300"},{"ID":"4","Country":"Sri Lanka","Value1":"320","Value2":"330"},{"ID":"5","Country":"Sri Lanka","Value1":"120","Value2":"90"},{"ID":"6","Country":"Sri Lanka","Value1":"420","Value2":"890"},{"ID":"7","Country":"China","Value1":"20","Value2":"890"},{"ID":"8","Country":"China","Value1":"430","Value2":"999"},{"ID":"9","Country":"Canada","Value1":"200","Value2":"319"},{"ID":"10","Country":"Canada","Value1":"1000","Value2":"29"}]
I want to use this JSON object as input to my D3.js graph.
When I try to create my D3 chart I get the error in my browsers log:
SyntaxError: Unexpected token < in JSON at position 0(…)
The following is my D3 code where i invoke the PHP file and try to parse the JSON:
d3.json("1.php", function(error, data) {
console.log(error);
//parsing operations
});
Any pointers would be appreciated. Thanks
I am using this rss.php file for rss feed but the problem is that it shows feed from just 2 tables not all the 4.Where is the problem?Feed is coming from famous people and econmicsandpolitics table only.
<?php
function connect() {
return new PDO('mysql:host=localhost;dbname=wg','root','', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$myarray = array('scienceandtechnology','economicsandpolitics','famouspeople','yetosbkistoryhe');
$key = array_rand($myarray);
$table= $myarray[$key];
$sql = "SELECT * FROM ".$table."";
$query = $pdo->prepare($sql);
$query->execute();
$rs_post = $query->fetchAll();
// The XML structure
$data = '<?xml version="1.0" encoding="UTF-8" ?>';
$data .= '<rss version="2.0">';
$data .= '<channel>';
$data .= '<title>google</title>';
$data .= '<link>http://www.google.com</link>';
$data .= '<description>io</description>';
foreach ($rs_post as $row) {
$data .= '<item>';
$data .= '<title>'.$row['title'].'</title>';
$data .= '<link>'.$row['content'].'</link>';
$data .= '<description>'.$row['summary'].'</description>';
$data .= '</item>';
}
$data .= '</channel>';
$data .= '</rss> ';
header('Content-Type: application/xml');
echo $data;
?>
You are here using it statically from table names i have almost same kind of problem but in my case the table name is also dynamic So use it according to your relevance
$sql = mysql_query("select name from sections order by rand()");
$datadisplay = array();
while ($row= mysql_fetch_assoc($sql)){
$section=$row['name'];
$sqldata = mysql_query("select title,summary from ".$section." order by ID limit 2");
while ($rowdata= mysql_fetch_assoc($sqldata)){
$datadisplay[] = $rowdata;
}
}
so here what i am doing is i fetching table names from sections and after that using those table names to fetch data from table and then storing that data into another array which then can be used to get rss data
If I understand correct it may help you ,
$pdo = connect();
$myarray = array('scienceandtechnology','economicsandpolitics','famouspeople','yetosbkistoryhe');
foreach ($myarray as $table) {
$sql = "SELECT * FROM ".$table."";
$query = $pdo->prepare($sql);
$query->execute();
$rs_post = $query->fetchAll();
foreach ($rs_post as $post) {
// echo something
}
}
I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch
filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);