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.
Related
i have a small problem with my php code.
i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.
<?php
$returnData = array();
class Clients
{
public function readAll(){
$query = "SELECT * FROM clients";
$result = $this->con->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$returnData['clientsList'][] = $row;
}
return $returnData;
}
else{
echo "No found records";
}
}
}
if ($auth->isAuth()){
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientsObj->readAll();
}
echo json_encode($returnData);
?>
and the result is like that, but without clietslist
{
"message": "you are loggedin, so is ok"
}
Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.
You need to get return value of function in a variable:
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] = $clientsObj->readAll();
$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.
I suggest you to read about variable scope in php.
https://www.php.net/manual/en/language.variables.scope.php
Now, You will need to store returned value from function in a variable
like this
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray = $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];
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
I'm trying to update a field on my database with PHP and AJAX
I have tested and found that the correct data is being sent, but the PHP that is handling the update is not working correctly.
All that happens is that I get the else response in conditional.
I need to update the DB depending on what the user input is.
Like I said, all I get for the response is the else response.
$youruname = $_POST['youruname'];
$selectedplayer = $_POST['selectedplayer'];
$selPlayerUname = $_POST['selPlayerUname'];
$flag = "";
$itStatus = "";
$checkit = mysqli_query($conn,"SELECT it FROM login WHERE uname='$selPlayerUname'");
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
}
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));
mysqli_free_result($checkit);
mysqli_close($conn);
There is something confusing here. You have a loop and after loop conditionals. Shouldnt your update query be inside a loop like:
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
}
Your $iStatus gets the last value from the database since its in the loop and then you check in conditionals
If above does not help then check your $_POST values to see if any of them are blank or null and do the query on PHPMyAdmin see if it actually returns anything.
mysqli_query requires you to pass the connection.
I wasn't doin that.
When I passed the values to the query directly, I figured it out.
Thank you very much for the help everyone
<?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