I've got a MySQL database of offices with geo data. I'm trying to get a list of the office cities into a JavaScript array. For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null. I'm just running my JavaScript function "query()" in console after the page loads.
Here's my JavaScript.
function query() {
$.ajax({
url: "query.php",
method: "POST",
dataType: 'json',
success: function(data) {
let output = JSON.parse(data)
console.log(output)
}
})
}
Here's query.php
<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Here's database.php. I'm able to write to MySQL using this PHP, so I assume it's correct.
<?php
$hostname = "hostus.mostus.com";
$username = "name";
$password = "pw";
$database = "db";
$link = mysqli_connect($hostname, $username, $password,$database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
When I run query() in the console, it responds "undefined" then null.
Your sql is invalid.
I would also init the $result_array before. Currently if the result is empty, you are returning null.
<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);
$result_array = [];
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Related
Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.
Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?
AJAX (Jquery):
function readLine(name, firstname) {
$.ajax({
type: "post",
url: "./php/readLine.php",
dataType: 'json',
data: { name: name, firstname: firstname },
success: function(data) {
console.log(data);
}
error: function(data) {
console.log("An error occured!");
}
});
}
PHP:
<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
Thanks for your help.
You can do it using PDO with prepared statements, that'll make sure the user input is made safe. Like this:
try {
$db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
Move the first 5 lines into an include, then you only need this code once.
Firstly, you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. I cannot emphasise this enough, an attacker would be able to wreak havoc on your database with the code you currently have.
You should use something like the following (taken from the page linked above, and this comment on the same page). Note that I have removed the intval calls to your POSTed data, as I assume they are strings rather than integers.
$to_encode = array();
$mysqli = new mysqli("localhost", "root", "password", "myDB");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE firstname=? AND name=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $_POST['firstname'], $_POST['name']);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
/* now you can fetch the results into an array - NICE */
while ($myrow = $result->fetch_assoc()) {
// use your $myrow array as you would with any other fetch
$to_encode[] = $myrow;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($to_encode);
$stmt = $con->prepare("SELECT * FROM table1 WHERE name=? and firstname=?");
$stmt->bind_param($name ,$firstname);
// set parameters and execute
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$stmt->execute();
$stmt->bind_result($to_encode);
$stmt->fetch();
echo json_encode($to_encode);
I have an AJAX request to fetch the data from MySQL. On request the result variable in the success part contains an empty string, "". If I change the dataType to json I don't get any results in return.
$.ajax({
url: "test.php",
dataType: 'text',
success: function(result) {
alert(result);
}
});
<?php
$con = mysqli_connect("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM 'tabel_name'";
$result = mysqli_query($con, $sql);
?>
What could be the reason for this empty string as a result? I have data in the table and I don't get any exceptions.
In your php code
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM 'tabel_name'";
$result=mysqli_query($con,$sql);
$resultant_array = array();
$index = 0;
while($row = mysql_fetch_array($result)) {
foreach($row as $column => $val) {
$result[$index][$column] = $val;
}
$index++;
}
echo json_ecode($resultant_array);
?>
This way you will get response data within your success promise of ajax
basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);
Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$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);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$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);
?>