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>
Related
I want to retrieve a row value from database.
Since we need serverside to access database we have to use PHP to retrive the value but I am not sure how to use this php in a .js file.
This is what I am trying but it does not work.
The reason is simple.. we can not write PHP inside a javascript file.
file.js:
<?php
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
?>
$( document ).ready(function() {
var addressFrmPHP = "<?= $address; ?>";
var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});
How can I assign the php $address variable to javascript addressFrmPHP variable?
You have to create two files as shown below
getdata.php
<?php
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
echo $address;
?>
file.js
$( document ).ready(function() {
/* AJAX for get data from php page */
$.post('getdata.php', function(address) {
var addressFrmPHP = address;
});
var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});
you have to do like this
test.php
<?php
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
echo '<script> var address= '.$address.';</scrpit>';
?>
<script type='text/javascript' src='js/file.js'></script>
file.js
$( document ).ready(function() {
var addressFrmPHP = address;
var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});
Create One file Getdata.php and write the below code:
<?php
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = 'nirav4491';
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="application/javascript">
$(document).ready(function() {
var addressFrmPHP = '<?php echo $address; ?>';
var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
alert(url);
});
</script>
</head>
</html>
Im using mysql database. I want to make a link that link to a php page.
<?php
$connection = mysql_connect("localhost","root","");
mysql_select_db("scratchdisk",$connection);
$sql = "SELECT * FROM note";
$result = mysql_query($sql);
echo "<table>";
echo "<tr><td>#</td><td>Title</td><td>Action</td></tr>";
while($row=mysql_fetch_assoc($result)){
echo "<tr><td>".$row['#']."</td><td>".$row['Title']."</td><td><a href='view.php' id='view'>View</a></td></tr>"; }
echo "</table>";
?>
I want to display the next page base on my $row['#'] but the same view.php file.
You can use this code:
<?php
$connection = mysql_connect("localhost","root","");
mysql_select_db("scratchdisk",$connection);
$sql = "SELECT * FROM note";
$result = mysql_query($sql);
echo "<table>";
echo "<tr><td>#</td><td>Title</td><td>Action</td></tr>";
while($row=mysql_fetch_assoc($result)){
echo "<tr><td>".$row['#']."</td><td>".$row['Title']."</td><td><a href='view.php?id=" . $row['#'] . "' id='view'>View</a></td></tr>"; }
echo "</table>";
?>
In view.php
if(isset($_GET['id']) && !empty($_GET['id'])){
//Write logic here
$id = $_GET['id'];
}
I'm new at php. I get the last id from database. For each id I want the state and the link. I'll check if state == 1, then get the content of the link (there's JavaScript variable that I need that is in the content of link). I'll send that variable with location.href.
Then I get that variable with $_GET in the second page. I want to store that var into database, then come back to first page and get the second link from the database and again do the same works.
How can I send the $j into second page for saving the x_cor and y_cor, and how to increase the $j when it comes to first page again?
<html>
<head>
<title>firstpage</title>
</head>
<body>
<?php
include_once ('simple_html_dom.php');
include_once ('split_unicode_function.php');
// getting the last id from db
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$sql = "SELECT id FROM netbarg ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $connection);
$rows = mysql_fetch_array($result);
$last_id = $rows['id'];
// getting id and link for each column
for ($j = 1; $j <= 2; $j++)
{
$select_db = mysql_select_db("kk", $connection);
$id = "SELECT state FROM `table` WHERE id='$j' ";
$result = mysql_query($id, $connection);
$row = mysql_fetch_array($result);
echo $state = $row[0] . '<br />';
// getting link
$link = "SELECT link FROM `table` WHERE id='$j' ";
$result = mysql_query($link, $connection);
$rows = mysql_fetch_array($result);
$link = $rows[0];
// (state is just 1 or 2)check if the state is 2 or not...
if ($state == 1)
{
$f = file_get_contents($link);
echo "<div>$f</div>";
}
}
?>
<script>
$("body").hide();
location.href ='secondpage.php?val='+point0+;
</script>
</body>
</html>
second page
<html>
<head>
<title>second page</title>
</head>
<body>
<?php
if (isset($_GET['val']))
{
$hat = $_GET['val'];
echo $hat;
$coords = trim($hat, '()');
// echo $coords.'<br />';
$a = array();
$a = explode(",", $coords);
var_dump($a);
echo $long = $a[0];
echo '<br />';
if ($long == "undefined") $lat = "undefined";
else echo $lat = $a[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$update = "UPDATE `table` SET `x_cor`='$long',`y_cor`='$lat' , `state`='2' WHERE `id`='$j' ";
$insert_todb = mysql_query($update, $connection);
if ($insert_todb) echo "coordinates has been updated", '<br />';
}
}
?>
<script>
location.href ='firstpage.php';
</script>
</body>
</html>
if get the last insert id use mysqli_insert_id($con);
it return last insert id from database using this geted id you can
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.
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