I have a simple data retrieval PHP file from Mysql and encodes in JSON string. The code below returns the result as expected
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($con));
} else {
$res = mysqli_query($conn,$sql);
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
echo json_encode(array("result"=>$result));
$conn->close();
?>
Sample Result...
{"result":[{"_id":"1","course_name":"Quail Valley","address":"12565 NW Aerts Rd.","city":"Banks","state":"OR","zipcode":"97106","phone":"5033244444"},...]}
My goal is to use the variable that was passed to PHP and based on it's name call function. I can't seem to figure out what I'm doing wrong!
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
function Course() {
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($conn));
} else {
$res = mysqli_query($conn,$sql);
}
$results = array();
while($row = mysqli_fetch_array($res)){
array_push($results,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
return $results;
}
$result = call_user_func(Course());
// OR... $result = call_user_func($tablename());
echo json_encode(array("result"=>$result));
$conn->close();
?>
Here is the output...
Error description: {"result":null}
As you can see in the doc of php.net http://php.net/manual/fr/function.call-user-func.php
The function accepts a string as a parameter (see the examples).
So it should be call_user_func('Course')
Preferred way is directly go for:-
$result = Course();
But if you want to use call_user_func() then use like below:-
$result = call_user_func('Course');
It's because it take a callback as a string :-call_user_func
Related
I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors.
I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.
Here is my code so far hope you can help:
public function db_query() {
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
$mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);
// create string of queries separated by ;
$query = "SELECT name FROM mailbox;";
$query .= "SELECT port FROM mailbox";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
while ($row = $result->fetch_row()) {
echo $row[0];
}
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}
Note: I did not add the parameter for the query just for testing
purposes.
public function db_query($mysqli) {
$return = [];
$result = mysqli_query($mysqli, "SELECT name FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
$result = mysqli_query($mysqli, "SELECT port FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
return $return;
}
simple, clean, efficient, always works
I would like to see where my code is incorrect. I want to store values from my database as a php array. Then I'd like to store the individual parts of the array as separate variables. Here is my code:
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = mysqli_fetch_row($result);
$comment0 = $comments[0];
$comment1 = $comments[1];
$comment2 = $comments[2];
$comment3 = $comments[3];
$comment4 = $comments[4];
$comment5 = $comments[5];
$comment6 = $comments[6];
$comment7 = $comments[7];
$comment8 = $comments[8];
$comment9 = $comments[9];
?>
This will run your mysql query and add each comment to an array of comments, then print the array.
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = array();
while($comment = mysqli_fetch_row($result)){
$comments[] = $comment;
}
print_r($comments);
?>
not sure if you are in console or through web server.
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = mysqli_fetch_row($result);
foreach($comments as $comment){
echo print_r($comment,1).'--------------\r\n<br>\r\n';
}
?>
this is called a loop. loop is your friend.
I'm trying to build a very basic API, I've got a query that pulls data from a MySQL view, I can echo the query out as json no problem but I want to put the query in a function in order to be able to call it from the API script...I'm just having some trouble putting the code into a function.
Here's the ode that works.....
<?php
$servername = "database.com";
$username = "username";
$password = "password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["year"]. " - " . $row["Month"]. " " . $row["the_days"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
...and this is my attempt to put it into a function (that doesn't work!)...
//Connection as above
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
available_dates();
$conn->close();
?>
I've just started with functions so I expect my errors to be quite comical!
...do I need to use echo to call the function?
you are not returning anything,you should assign return value to some thing.You should call your function like this.
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
$result=available_dates();
You are doing nothing with the return value of your function.
You can echo it or put it in a variable.
echo available_dates();
or
print_r(available_dates());
or
$results = available_dates();
You're returning an array in your code:
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
You should simply echo the json_encode like this:
echo json_encode($encodeArray);
And then take care of the formatting/displaying (alternatively, you could do it like in your first example and echo back the output ready for displaying):
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row["year"]. " - " . $row["Month"]. " " . row["the_days"].<br>";
}
and then
echo json_encode($encodeArray);
i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?
Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.
I already know how could I UPDATE this values, but I am a litle confused about how can I get this current values.
So, here's my code:
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($result != '1') {
echo '<div>IT'S TRUE</div>';
}
echo '<div>IT'S FALSE</div>';
}
?>
The return value of mysql_query() is actually an resource identifier and not the data, you request. To get the actual data, you have to fetch it first, e.g., by using mysql_fetch_assoc():
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($row = mysql_fetch_assoc($result)) {
if( $row['ativo'] != 1 ) {
echo '<div>IT\'S TRUE</div>';
} else {
echo '<div>IT\'S FALSE</div>';
}
}
I also corrected the missing escaping of ' inside your string. See the highlighting in your question, what went wrong there.
You have to fetch the result from that query. Like this:
$query = mysql_query("SELECT ativo FROM Spot", $db);
$result = mysql_fetch_array($query);
if ($result['ativo'] == 1) {
// is 1
} else {
// not 1
}
//RETURN RESULT
while ($row=mysql_fetch_array($result)) {
echo $row['ativo'];
}
first you have to use other quotes
not
echo '<div>IT'S TRUE</div>';
should be like
echo "<div>IT'S TRUE</div>";
second
your query returns a resoure id, so it never will be 1 ^^
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result)
{
die("ERRO" . mysql_error());
}
else
{
//RETURN RESULT
while ($data = mysql_fetch_assoc($result))
{
echo $data['ativo'] . "<br/>";
}
}
?>
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($row = mysql_fetch_array($result)) {
$value = $row['ativo'];
if($value!=1){
echo '<div>IT\'S TRUE</div>'; // escape special chars
}
else{
echo '<div>IT\'S FALSE</div>'; // escape special chars
}
}
?>