MYSQLI: Get result of query from Ajax call to HTML - php

I am trying to get the result of a database query, which will almost always contain more than one row of data, from an Ajax call in an HTML file, back to the HTML file so that I can display it.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title>My Webpage</title>
<script type="text/javascript">
//Function for getting data from database
function getData() {
$.ajax({
url: "get_data.php",
type: "GET",
success: function(data) {
alert("Finished!");
}
});
}
</script>
</head>
</body>
<!--I'd like to put a table of data here-->
</body>
</html>
get_data.php:
<?php
include "action.php";
$sql_query = "SELECT * FROM " . TABLE;
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
echo executeQuery($sql_query, $mysqli);
?>
action.php:
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("TABLE", "data_set");
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli) {
if(mysqli_query($mysqli, $sql_query)){
echo nl2br("\n\nQuery executed successfully: $sql_query");
} else {
echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
}
}
?>
I can't seem to figure out how to get the result of the query from action.php to 'get_data.php, back to the original Ajax call fromindex.htmlso that I can build my table. I've tried just usingecho` with the result of the query, but that did not work because there was an error for the conversion of an object to a string.

I don't see any return value from your executeQuery function. The mysqli_query function returns a mysqli_result object, or the boolean false if anything fails. You can use this mysqli_result object to get the data which you require and put it into an array. This array should be encoded into a json response, which is a format which Javascript understands.
So for example:
function executeQuery($sql_query, $mysqli) {
$rows = [];
$result = mysqli_query($mysqli, $sql_query);
if ($result === false) {
// Do something if anything goes wrong here like throwing an exception
}
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
Then you can call this function to get the data and convert it to json as follows:
$rows = executeQuery($sql_query, $mysqli);
echo json_encode($rows);
This is the most basic of basic ways, however this exact implementation is not recommended. Outputting the real column names for a table is a vulnerability because everyone can see them, I'd loop through them and change them before using json_encode.

You defined TABLE but where is your DATABASE name? You can't just write down echo in every places. You have to use mysqli_fetch_array function to get the result as array and then send that as json. I just fixed the whole code in one script, guess, it will help.
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "YOURDATABASE");
define("TABLE", "YOURTABLENAME");
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if ($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli)
{
$result = mysqli_query($mysqli, $sql_query);
if ($result) {
//You have to run mysqli_fetch_array to get real data as array
return mysqli_fetch_array($result);
}
}
$sql_query = "SELECT * FROM " . TABLE;
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);
//Check database connection
if ($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
//echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//after getting the result send output to brower with json encode and then from your ajax response
// You can handle json data easily.
// And for json response you can't just write echo from everywhere in script. Send either die on failure or result on success
$result = executeQuery($sql_query, $mysqli);
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
exit();

Related

php function with mysqli

This is my fonction.php :
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
But it does not works with my code when I want to call this function :
<?php
include("fonctions.php");
?>
<html>
<form name="inscription" method="post" action="form.php">
xxx : <input type="text" name="xxx"/> <br/>
xxx: <input type="text" name="xxx"<br/>
<input type="submit" name="valider" value="OK"/>
</form>
<?php
if (isset ($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
connect();
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
}
?>
</body>
</html>
Before I was using mysql_connect and it was more simple, my fonction was like this :
<?php
function connect(){
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('MaBase', $base) ;
}
?>
What is the best way to create a good include with my mysql params ? THanks all for any help.
Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...
You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.
function connect($sql){
For defining it, and then to call it
$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);
You'll also need your function to return some sort of value.
What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)
This is written once, and require_once()'d all across 15 web apps for the college I work at.
To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff
database.class.php
//databaseconnection
class DatabaseConnections{
function connect($databaseNaem){
try{
return $connection=mysqli_connect("localhost","user","password",'database');
}catch(Exception $e){
echo 'Message:'.$e->getMessage();
}
}
function CloseConnection($dataObject){
if(mysqli_close($dataObject)){
return 1;
}else{
echo "coudn't Close the Database Connection";
}
}
function convert($connection , $vari){
return mysqli_real_escape_string($connection,$vari);
}
}
//queryclass
class Query{
function queryNoresult($stmt){
if($stmt->execute()){
return 1;
}
}
function queryNumOfRows($stmt){
$stmt->execute();
$result = $stmt->get_result();
return mysqli_num_rows($result);
}
function QueryResult($stmt){
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
function illcallothers($stmt,$callto){
if($callto == 1){
return $this->queryNoresult($stmt);
}if ($callto==2) {
return $this->queryNumOfRows($stmt);
}
if($callto == 3){
return $this->QueryResult($stmt);
}
}
}
as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters
Created statement
The function number
there 3 option in this
if you call $query->illcallothers($stmt,1) this call the function
only for execute best for delete and insert because it's return 1 if
it's success
if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while
if you call $query->illcallothers($stmt,3) this will return result set from your query
Now lets go to your problem execution
//first you have to require the database file
require_once('database.class.php');
//Then you have to create object from them
$mymainObj = new DatabaseConnections();//obj from database
$connetion = $mymainObj->connect('databasename');//this will return a connection Object
$stmt = $connection->stmt_init(); //then the statement you need the connection object to this
$query = new Query();//object from the query class
//i am not going to put form part in here it will get messy
$titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection
$auteur=$mymainObj->convert($connection,$_POST['xxx']);
//now you have create the sql
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$author);
if($query->illcallothers($stmt,1)){
echo "Query Success";
}
}
It should be,
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
?>
Your query should be,
<?php
if (isset($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
$connection = connect();
if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);
if($result){
echo "done";
}else{
echo "faild";
}
}
}
?>
You should take a tour/learn the basics of OOP
It seems like all the above answers missed that you have two variables with the same name:
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
Both are called $xxx
IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)

Trouble retrieving data with PHP and SQL

I'm struggling to retrieve data from a table holding basic information. I've tried to use odbc_fetch functions but I couldn't get them to work. Could someone show me how to retrieve the data from a certain row
<?php
session_start();
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<?php
$employeeNumber = $_SESSION["user"];
$connect=odbc_connect("CoveringSystem", "", "");
$getData="SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'";
$result = odbc_exec($connect, $getData);
## //I've tried to add the odbc_fetch functions here\\ ##
echo $employeeNumber;
echo $firstName;
echo $lastName;
?>
</body>
</html>
Check this with mysqli :
// First connect to database
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Than make your query
$getData=mysqli_query($con,"SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'");
//Count row returned
if(mysqli_num_rows($getData)>0){
while($row=mysqli_fetch_assoc($getData)){
$firstName=$row['FirstName'];
$lastName=$row['LastName'];
//then you can do whatever you like with your data
}
}else{
}

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

PHP - Mysqli_query is successful, but return empty rows

I have a table full of names and I have a stored procedure that returns all of the names. However it is not doing what I expect it to do and I can't pinpoint the problem even with log. Instead of getting a drop down list of actual names, I'm getting a drop down of blank values as if I can actually select a value, but console.log displays a empty value, which I'm assuming means it's null
connection.php
<?php
require 'credentials.php';
include '../ChromePhp.php';
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
ChromePhp::warn('something went wrong!'); // didn't reach here
}
?>
This calls retrieveAllPokemonNames.php
<?php
include '../database/retrieveAllPokemonNames.php';
while ($row = $result->fetch_assoc()){
echo "<option value= ".$row[0].">".$row[0]."</option>";
}
?>
retrieveAllPokemonNames.php
<?php
require 'connection.php';
$sql = "CALL sp_selectAllPokemonName";
if ($result = $con->query($sql)){
ChromePhp::log('query is successful'); // output
ChromePhp::log($result); // log outputs a Object { current_field: null, field_count: null, .....etc }
}
?>
The SQL query works fine when I call it in phpMyAdmin's interface and sp_selectAllPokemonName is basically
Select * From PokemonName
which returns ~100 rows

Returning a value from database after writing in data as function return

I'm sending my database a string to write into a database. I have 2 fields, one called num that's set to auto increment, and one called cards into which my string is written. So far I've been able to get my php to write the variable into the database, but now I would like it to return the num associated with it, so I can use it on my page. Can anyone help me how to write that, I'm new to php. I guess I need another sql query? (I want it to echo the num column of the row I've just written in, instead of "Records added successfully.").
php:
// Attempt MySQL server connection *
$link = mysqli_connect
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$cards = mysqli_real_escape_string($link, $_GET['cards']); //get data from javascript
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
mysqli_query($link, $sql);
if(mysqli_query($link, $sql)){
echo mysqli_insert_id($link);
} else {
echo "failed!";
}
// Close connection
mysqli_close($link);
?>
js:
function writeDraft() {
$.ajax({
url: 'php/write.php',
type: 'get', //data type post/get
data: {
cards: output
},
complete: function (response) {
$('#draftNum').text(response.responseText);
},
error: function () {
console.log('Bummer: there was an error!');
}
});
return false;
}
writeDraft();
mysqli_insert_id() will do the job
if(mysqli_query($link, $sql)) {
echo "Records added successfully with id: ".mysqli_insert_id($link);
}
$sql = "SELECT * FROM drafts";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
if(mysqli_query($link, $sql)){
echo $num+1, " Records added successfully.";
}
// Close connection
mysqli_close($link);
?>

Categories