I'm currently making a webpage which is meant to show all it's content from the database. So I made an SQL command which selects the data needed for only 1 particular field on the webpage.
Is it possible to make the SQL command so that it get's all the content for the page at once and that ill still be able to display it separately?
If so, how? Thanks
function dbGet() {
global $conn;
global $return;
$sql = SELECT * FROM testTable;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$return = $row["text"];
return $return;
}
}
else {
echo "0 results";
}
// $conn->close();
}
You can use in this way through which you can identify records has been there or not.
function dbGet() {
global $conn;
// I am not sure what is the datatype of $return here.
// if it's having a predefined format,
// please push the records into $return instead of creating as an array,
// which will be taken care by framework if any you are using.
// global $return;
$return = array('status' => false, records => []);
$sql = "SELECT text FROM testTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$return['status'] = true;
while($row = $result->fetch_assoc()) {
$return['records'][] = $row["text"];
}
}
// $conn->close();
return json_encode($return);
}
Just echo the results inside while loop instead of returning in whatever format you wish
If you are using php, you can try something like
echo $row["text"];
Hope it helps
Let me know if you require any further help
First you should fix your return code as #AbraCadaver mentioned :
$return[] = $row["text"];
Then you can use foreach in your html :
<?php
foreach($return as $r){
echo $r['text'];
}
?>
I think a Json encoding : json_encode will work well.
Try this: http://php.net/manual/pt_BR/function.json-encode.php
Related
I have a pretty simple php web service, but it is only returning one row. I need to return all rows in the table. I'm am iOS Developer trying to do some of the backend web services programming so I would consider myself a beginner in this subject. Below is my code, is there something I am missing that makes it return all rows?
<?php
require_once "../database/config.php";
header("Content-type: application/json");
$sql = "SELECT * FROM ft_client";
$res = mssql_query($sql);
if (mssql_num_rows($res)) {
$op = mssql_fetch_assoc($res);
$op['response'] = 200;
} else {
http_response_code(420);
$op = array('response' => 420);
}
echo json_encode($op);
mssql_close();
?>
I'm not a beginner in SQL and I know that the SELECT * should be grabbing everything from the table, I'm sure its a simple fix... a little help, please?
Heres what I ended up with after some help from Jon Stirling. While loop grabs all rows and adds to the array $arr, which I then echo the $arr and get my results.
<?php
require_once "../database/config.php";
header("Content-type: application/json");
$sql = "SELECT * FROM ft_client";
$res = mssql_query($sql);
if (mssql_num_rows($res)) {
while($op = mssql_fetch_assoc($res))
{
$arr[] = $op;
}
echo json_encode($arr);
} else {
http_response_code(420);
$op = array('response' => 420);
echo json_encode($op);
}
mssql_close();
?>
This code should return an array containing data from a WAMP server containing some entries about followers. Unfortunately it doesn't. Any help please?
<?php
include('ConnectionManager.php');
function getfollowers()
{
print "check";
//String query
$query="SELECT * FROM `followers` order by 'followerid'";
//execute query
$result=mysql_query($query);
//3mel array isma followers
$followers=array();
//jeeb number of rows
if(mysql_num_rows($result))
{
while($followers=mysql_fetch_assoc($result))
{
$followers[]=$followers;
}
return $followers;
}
}
?>
You're re-declaring $followers inside your loop. Change it to something else
while($row = mysql_fetch_assoc($result)) {
$followers[]=$row;
}
your issue is:
$followers[]=$followers;
you are overriding it.
while($row=mysql_fetch_assoc($result))
{
$followers[]=$row;
}
should fix the issue
I'm a beginner in PHP5 and I'would like to have some help to get the code correct. Check the code and I'will be grateful for your support.
index.php:
if ($tag == 'AfficherMesAnnonce')
{
$Id_Utilisateur= $_GET['Id_Utilisateur'];
$annonce = $db->MesAnnonces($Id_Utilisateur);
if ($annonce)
{
$response["success"] = 1;
$response["annonce"]["Departure_place"] =$annonce["Departure_place"];
$response["annonce"]["Departure_date"] = $annonce["Departure_date"];
$response["annonce"]["Arrival_place"] = $annonce["Arrival_place"];
$response["annonce"]["Path_type"] = $annonce["Path_type"];
echo json_encode($response);
// annonce stored successfully
}else
{
$response["error_msg"] ="No annonce found";
return false;
echo json_encode($response);
}
}
DB_Function.php:
public function MesAnnonces($Id_Utilisateur)
{
$result = mysql_query("SELECT * FROM annonce WHERE Utilisateur_Id_Utilisateur = $Id_Utilisateur") or die(mysql_error());
// check for result
while($row = mysql_fetch_assoc($result))
{
$dd[]=$row;
}
$response=array('annonce'=> $dd);
return $response;
}
and thank you in advance.
You DB function is creating the dd array as a collection of rows, and then nesting that as an element of what's returned. But in your calling script you're assigning
$response["annonce"]["Departure_place"] = $annonce["Departure_place"]
--but the right side of that doesn't exist. You could instead assign:
$response["annonce"]["Departure_place"] = $annonce[0][0]["Departure_place"]
which would be the first row. You're not iterating through the rows in the client script, or using any kind of index to select a row.
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator";
$query.="SELECT thread_id FROM threads";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s\n",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------");
}
}while($mysql->next_result());
}
$mysqli->close();
?>
It doesnt work.. it doesnt go to the first if condition that identifies if it is a multiquery..
I have other question, ..why are multi_query() is useful..,
UPDATE:
Strict Standards: mysqli::next_result() [mysqli.next-result]: There is
no next result set. Please, call
mysqli_more_results()/mysqli::more_results() to check whether to call
this function/method in C:\xampp\htdocs\PoliticalForum2\test.php on
line 42
SOLVED:
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads;";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s<br/>",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------<br/>");
}
else
{
echo '<br/>';
}
}while($mysqli->more_results() && $mysqli->next_result());
}
$mysqli->close();
?>
You need a semicolon at the end of the first query.
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads";
mysqli::multi_query
The reason why you get this warning, is simply because you use a do...while loop that evaluates the condition after running the command block. So when there are no more results, the contents of the loop are ran one additional time, yielding that warning.
Using a while ($mysql->next_result())...do loop should fix this. (On a general note: Using post-test loops like you did is quite uncommon in database programming)
If code is poetry, I am trying to be Shakespeare!
You can fix it like this:
if ($res) {
do {
$mycon->next_result(); //// instead of putting it in a while, put it here
if ($result = $mycon->store_result()) {
while ($row = $result->fetch_row()) {
foreach ($row as $cell)
$flag = $cell;
}
///$result->close();
}
$sale=$sale+1;
} while ($sale > 2);
}
I got the answer for the same.
please find my function below.
public function executeStoredProcedureMulti($strQuery)
{
$yml = sfYaml::load(sfConfig::get('sf_config_dir').'/databases.yml');
$params = $yml['all']['doctrine']['param'];
$dsnName = $params['dsn'];
$arrDsn = explode(";",$dsnName);
$hostName = explode("=",$arrDsn[0])[1];
$schemaName = explode("=",$arrDsn[1])[1];
$this->dbconn = mysqli_connect($hostName, $params['username'], $params['password'], $schemaName);
//return if connection was created successfully
if($this->dbconn)
{
mysqli_set_charset($this->dbconn,"utf8");
//return true;
}
else
{
$this->nErrorNumber = mysqli_connect_errno();
$this->strErrorDesc = mysqli_connect_error();
return false;
}
//check if connection exists
if($this->dbconn)
{
/* close connection */
//execute the query
if($this->dbconn->multi_query($strQuery))
{
//create table array in dataset object
$dataSet = array();
do {
//store first result set
if ($result = $this->dbconn->store_result())
{
//create data table passing it the column data
$dataTable = new CDataTable($result->fetch_fields());
//parse through each row
while ($row = $result->fetch_row())
{
$dataTable->AddRow($row);
}
$result->free();
$dataSet[] = $dataTable;
}
if (!$this->dbconn->more_results()) {
break;
}
} while ($this->dbconn->next_result());
$this->dbconn->close();
//return the complete dataset
return $dataSet;
}
else//save the error to member variables
{
$this->nErrorNumber = $this->dbconn->errno;
$this->strErrorDesc = $this->dbconn->error;
}
}
return false;
}
This is working Need to create a Class CTableData. Please make one and it will work great
.
I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php