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);
Related
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();
?>
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
i want to fetch data from my database which is linked to the website,i have created a search box,whenever i enter a particular value in search box,it should display all the related content from the database.i have done the following code,it is not fetching the data from the database,it just shows a blank screen.
<?php
define('db_name','njgh');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
session_start();
$link=mysql_connect(db_host,db_user,db_password);
if(!$link)
{
die('couldnot connetc:'.mysql_error());
}
$db_selected=mysql_select_db(db_name,$link);
if(!$db_selected)
{
die('cant connect to db');
}
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM database WHERE Site_ID = '$value'";
$result = mysql_query($qry);
print_r($result);
mysql_query function return resource ID not your data , use mysql_fetch_array, mysql_fetch_object to get data
$value = ($_POST['searchtext']);
$result = mysql_query("SELECT * FROM database WHERE Site_ID = '$value'");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_* has been removed entirely as of PHP 7.0. Prevent SQL injection and use the mysqli statement class.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "njgh";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['searchtext'];
/* create a prepared statement */
if($stmt = $conn->prepare("SELECT * FROM database WHERE Site_ID =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['db_table_field_name'];
}
//or
$row = $result->fetch_assoc();
print_r($row);
} else {
}
/* close statement */
$stmt->close();
}
/* close connection */
$con->close();
?>
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.
Hope this will work for you......
<?php
define('db_name','sports');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
$link=mysqli_connect(db_host,db_user,db_password,db_name);
if(!$link)
{
die('couldnot connect:'.mysql_error());
}
function clean($str) {
$link=mysqli_connect(db_host,db_user,db_password,db_name);
$str = #trim($str);
if(get_magic_quotes_gpc())
$str = stripslashes($str);
return mysqli_real_escape_string($link, $str);
}
if(isset($_POST['searchtext'])){
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM cricket WHERE id = '$value'";
$qrydb = mysqli_query($link, $qry);
while($row=mysqli_fetch_array($qrydb)){
$name = $row['name'];
}
echo $name ;
}
?>
<body>
<form method="post">
<input type="text" name="searchtext">
<input type="submit" name="submit">
</form>
</body>
mysql_fetch_array() expects parameter 1 to be resource, boolean given in
<?php
mysql_connect ("localhost", "cab","a321") or die (mysql_error());
mysql_select_db ("ppwxpjey_mcidb");
$termOrd = $_POST['termOrd'];
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
while ($row = mysql_fetch_array($sql)){
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
?>
You've to run the query before passing it in mysql_fetch_array which expects resource as a parameter. So change your code like this,
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
$result = mysql_query($query) or die(mysql_error());
// This is where you're getting resource or throwing SQL error.
while ($row = mysql_fetch_array($result)){
// YOUR LOGIC.
}
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. Source : http://php.net/manual/en/function.mysql-query.php
So update your code as soon as you can.
Use mysqli_* or PDO . mysql_* is deprecated.
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MYSQLi or PDO_MySQL extensions. use prepared statement
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "cab"; //username
$password = "a321"; //password
$mysql_database = "ppwxpjey_mcidb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$termOrd = "%{$_POST['termOrd']}%";
$stmt = $conn->prepare("select * from booking where order_no like ? ");
$stmt->bind_param('s',$termOrd);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
while($row=$get_result->fetch_assoc())
{
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
}
$stmt->close();
$conn->close();
I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}