I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>
Related
I need help with the script. I want to show the result on page only when payload=1,if payload=0 do not display..
I've tried messing with mysql statements and I realized I need to change that in my script
this is my php:
<?php
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 ORDER
BY id DESC LIMIT 1 ";
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_assoc($retval)) {
echo "ID: " . $row["id"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
mysqli_free_result($retval);
echo "Fetched data successfully\n";
mysqli_close($conn);
my database is:
rooms
table:room1
ID
topic
payload
DateTime_created
and my index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
url: "vineri.php",
success:
function(data){
$('#listposts').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setInterval(sendRequest, 5000); // The interval set to 5 seconds
}
});
};
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
How do I get the result to display only when the payload is 1 ?
Try this code. I have re-written it for you. I run and tested it and it works for me.
First create table and insert as follows..
create table room1(ID int primary key auto_increment, topic varchar(30), payload int(11), DateTime_created timestamp);
insert into room1(topic, payload) values ('nancy topic 1', 1);
insert into room1(topic, payload) values ('nancy topic 2', 0);
here is vineri.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='1' ORDER BY ID DESC LIMIT 1";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
echo "ID: " . $row["ID"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
?>
index.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
// set for formality. though you can pass it to backend as a variable
var payload= 1;
var datasend = "payload="+ payload;
$.ajax({
type:'POST',
url:'vineri.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
WARNING: ID and id may not be the same as its cap intensive. You can see that In my table creations and sql queries I used ID instead of id. so becareful of capital and small letter that you use
Updated content
Sorry for being late. I don not understand properly what you want. Here is just what I guessed you want
if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
by using limit 1, only one rows will be retrieved.
if you want to get last rows with last id of 200 where payload is 0
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
Here is how I edited the code. you can test various sql queries that i commented
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='0'";
//if you want to get last rows with last id of 200 where payload is 0
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
//if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
$ID = $row["ID"];
$topic = $row["topic"];
$payload = $row["payload"];
$DateTime_created = $row["DateTime_created"];
}
if($payload ==0){
// insert record here
// return payload to the screen
echo "success<br><br>";
echo "ID: " . $ID. "<br>";
echo "Topic: " . $topic. "<br>";
echo "Payload: " . $payload. "<br>";
echo "Timestamp: " . $DateTime_created. "<br>";
}else{
//cannot insert record
echo "failed";
}
?>
I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.
I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>
Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.
I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML
I would like to use PHP variable in Java Script, I would like to get the variables of longitude and latitude which is returned from Select statement read from mysql database on the server.
here with my code below and what I have tried:
<?php
...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Latitude, Longitude FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
$latlong = " ". $row["Longitude"]. " , " . $row["Latitude"]. "<br>";
echo $long; //echo's -25.1234
echo $lat; //echo's 25.1234
echo $latlong; //echo's -25.1234 , 25.1234
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Tracker</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1200px; height: 750px;"></div>
<script language="JavaScript">
var locations = [
['FirstColumnString<br/> SecondColumnString', -25.038326, 25.038326], //I would like to pass Lat Long from PHP code from above
];
// I've tried
// ['FirstColumnString<br/>SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>,
// ['FirstColumnString<br/>SecondColumnString', <?php echo $latlong ?>,
// ['FirstColumnString<br/>SecondColumnString', "<?php echo $long; ?>", <?php echo $lat; ?>,
...
</script>
</body>
</html>
You should save your locations into an array first:
<?php
$locations = Array();
while($row = $result->fetch_assoc()) {
$loc = Array("lat" => $row["Latitude"], "long" => $row["Longitude"]);
$locations[] = $loc;
}
?>
then you can pass it to javascript:
<script>
var locations = <?php echo json_encode($locations) ?>;
// check what you've got:
console.log(locations);
</script>
you could then access your values like this:
var firstLocationLatitude = location[0].lat;
If you need to have your js-array exactly as you've posted change php to:
$clmString = "FirstColumnString<br/> SecondColumnString";
while($row = $result->fetch_assoc()) {
$loc = Array($clmString,$row["Latitude"],$row["Longitude"]);
$locations[] = $loc;
}
Try replacing
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
with
$long = $row["Longitude"];
$lat = $row["Latitude"];
and then
var locations = [
['FirstColumnString<br/> SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>],
];