PHP Array doesn't show all database items - php

I fixed now my PHP file and finally I have an output of my array. But the problem is, that I have three entry of textes in my database, but my array only shows two of them.
Function.php
public function listQuestion(){
$result = mysql_query("SELECT text FROM `questions`");
if(!$result)
{
echo "Database query failed: " . mysql_error();
}
$temp_array = array();
while ($row = mysql_fetch_array($result)) {
$temp_array[] = $row;
}
return $temp_array;
}
Index.php
else if ($tag == "question"){
// Request type is question
// list questions
$question = $db->listQuestion();
if ($question != false) {
// questions found
// echo json with success = 1
$response["success"] = 1;
$response["question"] = $question;
// $userlog = array();
// $userlog["question"]["text"] = $question["text"];
// array_push($response["question"], $userlog);
echo json_encode($response);
//echo json_encode(array("question"=>$question));
} else {
// questions not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Questions were not found!";
echo json_encode($response);
}
}
The output
{"tag":"question","success":1,"error":0,"question":
[{"0":"Ich lese gerne technische Zeitschriften.","text":"Ich lese gerne technische Zeitschriften."},
{"0":"Ich habe Angst im Dunkeln.","text":"Ich habe Angst im Dunkeln."},
{"0":null,"text":null}]} -> here should be 'Manchmal fühle ich mich hungrig.'
Any suggestions?
Roman

Related

How to create search boxes to spit out the results from a database

I am creating a result page using php to pull data from database.
I have been able to connect the database to my webspace and displayed the data.
Now , I would like to have the page not show all the data at once. I want to add an input field example "Origen= Los Angeles" "Destination = London" and then show the results based on that criteria.
This is my first time doing something like this so if this sounds like I should know this I'm sorry. I hope I can get some help.
<?php
// include connection settings
require_once "connect.php";
// display a list of flights
if(!empty($_GET) && !empty($_GET['name'])){
$query = "SELECT * FROM Flight_Information WHERE name LIKE ''".
$_GET['name']."".$_GET['name']."'";
} else {
$query = "SELECT ID, airlineName, departureAirport, departureDate, destinationAirport FROM Flight_Information";
} // END if
$result = $db->query($query);
if ($result) {
// ... display results in while loop
while ($row = $result->fetch_assoc()) {
echo '<li>'.$row['airlineName'].' '.$row['departureAirport'].''.$row['departureDate'].''.$row['destinationAirport'].'</li>';
} // END while
} else {
// if there was an error with your query
// this will display it
echo "SQL Error: " . $db->error;
} // END if
?>
</ul>
<?php
if (!empty($_GET) && !empty($_GET['Flight_Information_ID'])) {
$Flight_Information_ID = $_GET['Flight_Information_ID'];
$query = "SELECT * FROM Flight_Information WHERE ID =" . $Flight_Information_ID;
// perform the query
if ($result = $db->query($query)) {
// check we have a result
if ($result->num_rows > 0) {
// loop through and print out the results
while ($row = $result->fetch_assoc()) {
// output a title for each result
echo '<hr/><p>You have selected FriendShipper' .$Flight_Information_ID. ':</p> <ul>';
// loop through and output details for each item
foreach ($row as $key => $value) {
echo '<li><em>'.$key.'</em> = <strong>'.$value.'</strong></li>';
}
// output a horizontal rule under the result
echo '</ul><hr/>';
}
// num_rows = 0, no results found
} else {
echo "<p>No Flights Found " .$Flight_Information_ID. "</p>";
}
// if there was an error with your query, this will display it
} else {
echo "SQL Error: " . $db->error;
}
}
?>

Not able to get proper value and print respective msg

Below is my code , I am trying to append values of $vid ,and than next time when my file loads i am trying to find currently passed value of $vid in array $ids, but every time i am getting success msg ,where i am going wrong, am i not able to append values properly ?
process.php
session_start();
if(isset($_POST)) {
$reason_data = trim($_POST['abuse_data']);
if($reason_data == "Video is offensive")
{
$reason = 'a:1:{i:0;s:18:"' . $reason_data .'";}';
}
else
{
$reason = 'a:1:{i:0;s:19:"' . $reason_data .'";}';
}
$motive = trim($_POST['remark_data']);
$uid = trim($_POST['abuse_uid']);
$vid = trim($_POST['abuse_vid']);
if(trim($_SESSION['abuse_vdo_id']) == '')
{
$_SESSION['abuse_vdo_id'] = $vid;
$str = $_SESSION['abuse_vdo_id'];
}
else {
$str = $str."," .$vid;
$_SESSION['abuse_vdo_id'] = $str;
}
print_r($_SESSION['abuse_vdo_id']);
echo "break";
print_r($str);
$ids = explode(',',$_SESSION['abuse_vdo_id']);
echo "break 2";
print_r($ids);
if(in_array($vid, $ids))
{
echo "already abused";
}
else
{
echo "success";
$query = "INSERT INTO ".DB_PREFIX."reports ( reason, motive, uid, vid ) VALUES ( '{$reason}','{$motive}', '{$uid}', '{$vid}' )";
$result = mysql_query($query);
}
}

JSON Decode elements in file

Hi I am currently working on stripping out a json file and putting the elements into a database there are 26 entries in the json file using the following code I have been able to map the majority of the entries but am now in a position whereby certain elements in the json only occur in certain entries eg tags in the first 2 entries has a Name and cirrushq_id field but from the 3rd entry down has only a aws:autoscaling:groupName not present in the first 2 entries so my question really is how to modify the php such that it takes into account the fact that there may not be a Name or id for every entry and not subsequently break ?
here is the php
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$Name=$configurationItems["tags"]["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$configurationItems["tags"]["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= $configurationItems["tags"]["aws:autoscaling:groupName"];
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')")or die("Insert Failed ".((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
and the json
{
"fileVersion":"1.0",
"configurationItems":[
{
"configurationItemVersion":"1.0",
"configurationItemCaptureTime":"2014-12-05T10:22:51.751Z",
"configurationStateId":1,
"relatedEvents":[ ],
"awsAccountId":"",
"configurationItemStatus":"ResourceDiscovered",
"resourceId":"",
"ARN":"",
"awsRegion":"us-east-1",
"availabilityZone":"us-east-1b",
"configurationStateMd5Hash":"",
"resourceType":"AWS::EC2::Instance",
"resourceCreationTime":"2014-01-06T10:37:37.000Z",
"tags":{
"Name":"dbn.prod-us.wordeo.com",
"cirrushq_id":"instance_20"
},
as above for 2nd entry
3rd entry the same down to tags as follows
"tags":{
"aws:autoscaling:groupName":"ES-PROD-US-03-01-14"
},
using isset method as per answer
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
Use isset() to check the name or id exists or not.
Change the php foreach loop code like,
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
// remove the die if there is any error then it will go forward
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");

display data from phpmyadmin

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.

mysql query and encoding it in json format

I'm using this simple php code to encode the MySql query result in json format.
But Don't know why it is not giving me the desirable output.
I'm actually trying to get the employee details by entering their 'employee_number'.
<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
if (isset($_POST["employee_number"])) {
$employee_name = $_POST['employee_number'];
*/
//get a employee from employee_info table
$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
echo("Success !! Yoo");
$employee = array();
$employee["employee_number"] = $result["employee_number"];
$employee["employee_name"] = $result["employee_name"];
$employee["flag"]=$result["flag"];
// success
$response["success"] = 1;
// user node
$response["employee"] = array();
array_push($response["employee"], $employee);
// echoing JSON response
echo json_encode($response);
} else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
}else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
/*} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
*/
// echoing JSON response
echo json_encode($response);
?>
mysql_query is deprecated. Use mysqli or PDO instead.
make sure you format your query properly *note the spaces
$result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");
you could also just echo the $result as your employee array doesn't seem to do anything.
echo json_encode($result);

Categories