The code below should send back an json with informations in a Database.
It takes two parameters grade and subject. The problem ist, when I use parameters are not in the database behind everything works as expected no entry, but if it would get an answer from the database nothing appears. I mean really nothing. The values i need are there i tried this and no errors are logged into the logging file. As server runs apache2 with php5.6.22 on Debian. I don't know what i did wrong. Hopefully someone can help me.
The Code:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".$subject." AND grade=".$grade;
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die();
}
$response = array();
$response['books'] = array();
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row ["fullname"];
$book['ISBN'] = $row ["ISBN"];
$book['id'] = $row ["id"];
array_push($response['books'], $book);
}
$response['response'] = "1";
print(json_encode($response));
die();
I think this might be your problem:
array_push($response['books'], $book);
as far as I know you can't push a variable into a specific index of an array since no key is provided for the item being pushed.
It would be better to do this as follows:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".mysqli_real_escape_string((htmlspecialchars_decode($subject, ENT_QUOTES)))." AND grade=".mysqli_real_escape_string((htmlspecialchars_decode($grade, ENT_QUOTES)));
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die('sql failed');
}
$response = array();
$response['books'] = array();
$response['validator'] = 'valid';
$i = 0;
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row["fullname"];
$book['ISBN'] = $row["ISBN"];
$book['id'] = $row["id"];
$response['books'][$i] = $book;
$i++;
}
$response['response'] = "1";
var_dump($response);
//echo json_encode($response);
die();
Related
I'm working on an Activation Queue for new accounts on my website.
The system will work by iterating through an array with each new user account details in and then display them so the Admin can either accept or deny the account. To collect the account details and display them in an array I'm using the following piece of code, however I get the error "array_push() expects parameter 1 to be array, null given". I have no clue why this is being caused and I have tried various things previously suggested. Thanks in advance.
<?php
session_start();
require "classes.php";
$TF = new TF_Core ();
$ActQueueQuery = "SELECT username, surname, forename, joined FROM users
WHERE rank = 'Unactivated'";
if ($statement = TF_Core::$MySQLi->DB->prepare($ActQueueQuery)) {
$statement->execute();
$results = $statement->get_result();
}
if($results->num_rows == 0){
$data = 1;
}
else{
$_SESSION["ActQueue"] = "";
while($row = $results->fetch_assoc()){
$_SESSION["ActQueue"] = array_push($_SESSION["ActQueue"], array($row["username"], $row["surname"], $row["forname"], $row["joined"]));
}
$data = 0;
}
echo $data;
?>
<?php
session_start();
$_SESSION["ActQueue"] = array(); // define an empty array
require "classes.php";
$TF = new TF_Core ();
$ActQueueQuery = "SELECT username, surname, forename, joined FROM users
WHERE rank = 'Unactivated'";
if ($statement = TF_Core::$MySQLi->DB->prepare($ActQueueQuery)) {
$statement->execute();
$results = $statement->get_result();
}
if($results->num_rows == 0){
$data = 1;
}
else{
while($row = $results->fetch_assoc()){
$_SESSION["ActQueue"][] = array($row["username"], $row["surname"], $row["forname"], $row["joined"]); // check the change
}
$data = 0;
}
echo $data;
?>
"You are overwriting $arr_foundits on $arr_foundits = array_push($arr_foundits, $it->ID);. Remove the $arr_foundits = as array_push does not return the array but an int." Musa
I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
I'm querying a DB and want that query in string format, not object so what I've been doing is:
$StringHolder = "";
$sql = (some sql)
$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_row($result)){
$StringHolder = $row;
}
$StringHolder = implode($StringHolder);
Is there a better way to go about doing this? As you can probably tell I'm very new to this PHP.
So, one of my actual chunks of code is:
$connection = mysqli_connect($server,$username,$password,$databaseBuilding);
$tenantIdSql= "SELECT tenant_id FROM rooms WHERE room_num = '".$roomNum."'";
$tenantIdObj= mysqli_query($connection, $tenantIdSql);
$tenantID = "";
if($row = mysqli_fetch_row($tenantIdObj){
$tenantID = $row;
}
$tenantID = implode($tenantID);
Try something like this
$tenantID_array = array();
if($row = mysqli_fetch_row($tenantIdObj){
$tenantID_array[] = $row['tenant_id'];
}
$tenantID_str = implode(",",$tenantID_array);
echo $tenantID_str;
you just need to replace $tenantID = $row; with $tenantID = $row['tenant_id']; and if that is not working well then try $tenantID = $row[0];
I'm trying to fetch couple of single data in my server database but this is throwing some errors. The incoming data is correct. The search function just don't get completed.
Here's the code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
define('HOST','xxxxxxxxxxx');
define('USER','xxxxxxxxxxxx');
define('PASS','xxxxxxxxx');
define('DB','xxxxxxxxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
$post_id = $_POST['id'];
$buyer_mobile = $_POST['mobile'];
$buyer_name = $_POST['name'];
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysqli_query($con,$sql);
$owner_mobile = $row['mobile'];
$sql = "select name from user where mobile='$owner_mobile'";
$r = mysqli_query($con,$sql);
$owner_name = $row['name'];
$sql = "INSERT INTO flat_booking (post_id,owner_mobile,owner_name,buyer_mobile,buyer_name) VALUES ('$post_id','$owner_mobile','$owner_name','$buyer_mobile','$buyer_name')";
if(mysqli_query($con,$sql)){
echo "Success";
}
else{
echo "error";
}
mysqli_close($con);
}else{
echo 'error1';
}
What am I doing wrong here? Maybe this:
$owner_mobile = $row['mobile'];
Thanks in advance!
create table flatower and add mobile column
$post_id = 1;
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysql_query($con,$sql);
$row = mysql_fetch_array($res);
$owner_mobile = $row[0]['mobile'];
Your problem is this line:
$owner_mobile = $row['mobile'];
You have not created the $row variable. For this you would need to do something such as:
Do this first:
<?php
$row = array();
while ($result = mysqli_fetch_assoc($res))
{
$row[] = $result;
}
?>
This allows you to do this:
<?php
foreach ($row as $r)
{
var_dump($r); print "<br />"; // One row from the DB per var dump
}
?>
I have one problem, when i´m going to run the app i receive one System.err: no value for anotacoes!
I think my problem is on php code. If someone help me i'll appreciate a lot your help.
(Sorry for my bad english ;) )
<?php
// array for JSON response
$response = array();
$response1 = array();
mysql_connect("localhost","root",""); // host, username, password...
mysql_select_db("mobimapa"); // db name...
// check for post data
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT id_anotacao FROM processo_anotacoes WHERE id_processo = $pid");
// check for empty result
if (mysql_num_rows($result) > 0) {
//$response["processo_anotacoes"] = array();
$processo_anotacoes = array();
while ($row = mysql_fetch_array($result)){
array_push($processo_anotacoes, $row["id_anotacao"]);
// $processo_anotacoes["id_anotacao"] = $row["id_anotacao"];
// $processo_anotacoes["id_processo"] = $row["id_processo"];
// success
//$response["success"] = 1;
// user node
// $response["processo_anotacoes"] = array();
}
// echo json_encode($processo_anotacoes);
}
$ids = join(', ',$processo_anotacoes);
$result1 = mysql_query("SELECT * FROM anotacoes WHERE id_anotacao IN ($ids)");
if (mysql_num_rows($result1) > 0) {
$response1["anotacoes"] = array();
// check for empty result
while ($row1 = mysql_fetch_array($result1)) {
//$result1 = mysql_fetch_array($result1);
$anotacoes = array();
$anotacoes["id_anotacao"] = $row1["id_anotacao"];
$anotacoes["nome"] = $row1["nome"];
$anotacoes["descricao"] = $row1["descricao"];
// success
$response1["success"] = 1;
// user node
$response1["anotacoes"] = array();
array_push($response1["anotacoes"], $anotacoes);
}
// echoing JSON response
echo json_encode($response1);
}
?>
08-12 17:09:03.308: D/All Products:(806):
{"success":1,"processo":[{"data":"2013-07-17","id_processo":"1","nome":"Processo
1","imagem":"Later"},{"data":"2013-08-04","id_processo":"2","nome":"Processo
2","imagem":"Later"}]} 08-12 17:09:03.518: I/Choreographer(806):
Skipped 110 frames! The application may be doing too much work on its
main thread. 08-12 17:09:29.238: D/Processo clicado(806): 2 08-12
17:09:29.838: D/Single Product Details(806):
{"product":[{"data":"2013-08-04","id_processo":"2","nome":"Processo
2","imagem":"Later"}],"success":1} 08-12 17:09:30.028: D/Anotacoes
Details(806):
{"success":1,"anotacoes":[{"descricao":"teste","id_anotacao":"3","nome":"Anotacao
3"}]}
The problem is with the PHP variable being passed to the 2nd SQL query. This not the complete code; but if you understand it, it will solve your problem:
$anotacaos = array();
while ($row = mysql_fetch_array($result))
array_push($anotacaos, $row["id_anotacao"]);
$ids = join(',',$anotacaos);
$result1 = mysql_query("SELECT * FROM anotacoes WHERE id_anotacao in ($ids)");
while ($row = mysql_fetch_array($result1))
//do something...