How to sequentially push into array from MYSQL query? - php

The php and js are the following:
createRoomTable()
function createRoomTable(){
$.post('../include/returnRoomTable.php',{
//nothing to transmit
}).then((returnedTableMarkup) => {
returnedTableMarkup = JSON.parse(returnedTableMarkup)
console.log("data from returnRoomTable.php is ", returnedTableMarkup)
//$('#roomTableOutput').html(returnedTableMarkup)
})
}
<?php
session_start();
try{
$connection = new PDO('mysql:host=localhost;dbname=XXXX',
'XXXX','XXXXXX');
}catch(PDOException $e){
echo $e->getMessage();
}
$allRooms = $connection->query("
SELECT name
FROM raum
")->fetchAll(PDO::FETCH_NUM);
$indexLimit = count($allRooms);
$allSeats = [];
for($index = 0; $index < $indexLimit; $index++){
$allSeats = array_push($connection->query("
SELECT nummer
FROM arbeitsplatz
WHERE raum = '".$allRooms[$index]."'
")->fetchAll(PDO::FETCH_NUM));
}
echo json_encode ($allSeats);
?>
So currently, consolelog says the array is "null".
What I need is a flexible, two-dimensional array ("$allSeats") which takes each iteration from the MYSQL query and puts it into this array.
The problem is that I'm not very experiences with arrays in php, and I'm out of ideas how I can accomplish this.

Okay, so I found a solution to my problem myself:
The php now looks like this:
<?php
session_start();
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
$allRooms = $connection->query("
SELECT name
FROM raum
")->fetchAll(PDO::FETCH_NUM);
$indexLimit = count($allRooms);
$allSeats = [];
for($index = 0; $index < $indexLimit; $index++){
$currentQuery = $connection->query("
SELECT nummer
FROM arbeitsplatz
WHERE raum = '".$allRooms[$index][0]."'
")->fetchAll(PDO::FETCH_NUM);
array_push($allSeats, $currentQuery);
}
/*
$allSeats[] = $connection->query("
SELECT nummer
FROM arbeitsplatz WHERE raum = '".$allRooms[$index]."'
")->fetchAll(PDO::FETCH_NUM);*/
echo json_encode ($allSeats);
?>
And when I output this in my JS, I get an array of arrays containing the values.

Related

PHP Array in wrong format

I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:
array[0] = project1, project2, project3;
array[1] = item1, item2, item3;
and I'm having this:
array[0] = project1;
array[1] = project2;
array[2] = project3;
and so on..
this is what I've done so far:
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$proj_name = $proj['proj_name'];
$proj_beg = $proj['proj_beg'];
$proj_end = $proj['proj_end'];
array_push($info, $proj_name, $proj_beg, $proj_end );
}
}
echo json_encode($info);
my query result gave me these result:
["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]
and this is my $.getJSON code:
$.getJSON("includes/get_area.php",function(data){
console.log(data);
})
What am I doing wrong?
Try this one; this will add a list in each one of the three array indexes.
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$info[0][] = $proj['proj_name'];
$info[1][] = $proj['proj_beg'];
$info[2][] = $proj['proj_end'];
}
}
echo json_encode($info);

MySQL echos only one elemen

I've a problem with a MySQL script. The script should echo every element out of the table where "gruppe" is $gruppe. But I am only getting one single output.
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$gruppe = $_POST["gruppe"];
$mail = $_POST["mail"];
$betreff = $_POST["betreff"];
$nachricht = $_POST["nachricht"];
if (!empty($nachricht)) {
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_users WHERE gruppe = '$gruppe'");
for($i=0;$i<$sql->getRows();$i++)
{
$id_mail = $sql->getValue("id");
$mail_mail = $sql->getValue("email");
$ausgabe_mail = $mail_mail;
$sql->next();
}
}
}
?>
<?php echo $ausgabe_mail ?>
Your echo-statement is outside the loop. The loop fetches all email addresses, one by one, and stores them in $mail_mail and $ausgabe_mail. Each iteration of the loop overwrites the previous contents of both variables.
After the loop ends, you echo the last value of $ausgabe_email.
Retry with the echo inside the loop:
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$gruppe = $_POST["gruppe"];
$mail = $_POST["mail"];
$betreff = $_POST["betreff"];
$nachricht = $_POST["nachricht"];
if (!empty($nachricht)) {
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_users WHERE gruppe = '$gruppe'");
for($i=0;$i<$sql->getRows();$i++) {
$id_mail = $sql->getValue("id");
$mail_mail = $sql->getValue("email");
$ausgabe_mail .= ',' . $mail_mail;
$sql->next();
}
echo $ausgabe_mail;
}
}
?>
EDIT: as clarified, expanded the example with string concatenation and moved the echo outside the loop again.

PHP: A string, two arrays and 4 loops result in a 0

In my android app user can upload up to 5 images for an item they have in their collection.
This is what my android app java code is sending over to the PHP server via POST:
[user_id=83,
item_id=24,
item_number_of_photos=1,
item_image_filename_0=http://www.asdqwe.net/item_images/83_image_2014-02-07-16-44-12.jpg,
item_image_description_0=mouse]
This is the PHP Code that handles it:
if (!empty($_POST)) {
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
for ($x=0; $x<$item_number_of_photos; $x++) {
if(isset($_POST['item_image_filename_'.$x]) && !empty($_POST['item_image_filename_'.$x])) {
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
}
if(isset($_POST['item_image_description_'.$x]) && !empty($_POST['item_image_description_'.$x])) {
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
}
$query_add_item_photos = "INSERT INTO
product_photos (
product_id,
product_photo,
product_photo_added_by_user,
product_photo_description
)";
////////////////////////////////////////////////////////////
////ADD THE PHOTOS TO THE PHOTOS TABLE//////////////////////
////////////////////////////////////////////////////////////
try {
for($x = 0; $x<$item_number_of_photos; $x++) {
$query_add_item_photos+= " VALUES
(
:product_id,
:product_photo_filename_" . $x .",
:product_photo_added_by_user,
:product_photo_description_" . $x . "
)";
}
$input_parameters = array(
':product_id' => $item_id,
':product_photo_added_by_user' => $user_id,
);
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
$sth = $connection->prepare($query_add_item_photos);
$sth->execute($input_parameters);
} catch(PDOException $pe) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_response_server_error . $pe . $query_add_item_photos;
die(json_encode($response));
}
$response["success"] = $http_response_success;
$response["message"] = "WE MADE IT";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_bad_request;
$response["message"] = $http_message_bad_request;
die(json_encode($response));
$connection = null;
}
At the end when I run this, I get a PDO error saying that the query = "0".
I have only basic understanding of PHP so this is huge pain for me
Local Variables Issue
In your for loop, you are assigning values to $item_image_filenames[$x] array element and also to $item_image_descriptions[$x] array element.
for ($x=0; $x<$item_number_of_photos; $x++) {
...
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
...
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
But (assuming you have posted all of your code), these 2 arrays fall out of scope and disappear as soon as you exit your for loop. They weren't defined before your for loop, which means that they are being defined local to your for loop.
The result of this is that, later, when you attempt to reference these arrays, they don't exist, and they have no values. So, later on in your code...
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
... is going to result in assigning to $input_parameters values that don't exist.
To solve this problem, define $item_image_filenames and $item_image_descriptions before you enter your for loop. This way, they will continue to exist inside and after your for loop. You can do this:
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
// Define empty arrays so that I can use them throughout my code.
$item_image_filenames = array();
$item_image_descriptions = array();
for ($x=0; $x<$item_number_of_photos; $x++) {
...
String Concatenation Syntax
I also noticed that your line of code:
$query_add_item_photos+= " VALUES
...
... is not the correct way to do string concatenation in PHP. You want to use .= instead of +=. In PHP, strings are concatenated with ., as in the example: $string1 = $string2 . $string3;
Your code should instead be:
$query_add_item_photos .= " VALUES
...

php code of troubling getting multiple value

I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";

PDO - Call to a member function fetch() on a non-object?

I looked at all the other posts on this and none of them came up with exactly what my problem is so here we go:
$dbh stores my PDO connection, if I do a var dump on it, it returns:
object(PDO)#1 (0) { }
So I know my PDO connection is working. I then use $sth to hold my query:
$c = 2;
$sth = $dbh->query("SELECT * FROM table WHERE ID = " . $c);
Then to make sure this is working I did:
echo $sth->rowCount();
That return a value of 6. So I know it is grabbing some rows. My next step of checking my problem was to fetch a single row like the following:
$row = $sth->fetch()
print_r($row);
This returned a single row (as it should) with the $row array filled exactly how I would expect it (column names as keys and column values as the array value).
So we are good up to this point. Once I move $row = $sth->fetch() into a while loop my script fails the error it returns is: Call to a member function fetch() on a non-object
Here is my while loop:
while($row = $sth->fetch()){
//while loop stuff here
}
I know it has something to do with the condition of the loop because even when I comment out all the stuff in the middle it still isn't working. What am I doing wrong? Why won't this work? I'm beyond confused on this as it has worked in the past with all the PDO I have done but for some reason it is failing in this script.
If anyone has any tips or something that can help it would be greatly appreciated.
EDIT Since ninetwozero's post worked, I'm posting my class and basically everything I've got to get this figured out.
class html_elements {
var $units;
var $useMaps;
var $cid;
var $uid;
var $companyMoney;
var $currCity;
var $terminals;
var $termLocs;
var $cityArray;
var $cargoArray;
var $cargo;
var $tid;
var $truckArray;
var $load;
var $cityID;
var $cargoID;
var $xp;
var $gasPrice;
var $warning;
function __construct($u, $maps, $c, $userID, $cMoney, $dbh, $city, $tid, $xp){
$this->units = $u;
$this->useMaps = $maps;
$this->cid = $c;
$this->uid = $userID;
$this->companyMoney = $cMoney;
$this->currCity = $city;
$this->terminals = array();
$this->termLocs = array();
$this->cityArray = array();
$this->cargoArray = array();
$this->cargo = array();
$this->tid = $tid;
$this->truckArray = array();
$this->load = 0;
$this->cityID = array();
$this->cargoID = array();
$this->xp = $xp;
$this->gasPrice = 0;
$sth = null;
$sth = $dbh->query("SELECT * FROM tblCTerminals WHERE companyID = " . $c);
//THIS LOOP FAILS
while($row = $sth->fetch()){
$this->termLocs[] = $row['Location'];
}
}
Then in another file that has my class file included in it is:
$h = new html_element($u->get_units(), $u->get_maps(), $u->get_company(), $u->get_user_id(), $c->get_money(), $dbh, $u->get_city(), $u->get_truck_id(), $u->get_xp());
Each of those getters work, I tested them. Also $dbh is what is used my connection file that is included before anything else. So I know all of that is working.
I got to say that you've encountered a pretty interesting error, so let's try some things to pinpoint the cause:
if( $sth == null ) die('My sth is null at #1');
while( $row = $sth->fetch() ) {
if( $row == null ) die('My row is null at #2');
echo '<pre>';
print_r($row);
echo '</pre>';
}
Let me know what this tells you.
Edit:
$sql = 'SELECT * FROM tblCTerminals WHERE companyID = ' . $c;
if( intval($c) == 0 ) { die('Aaaaaaaaaa.......aaaaah.');
foreach ($dbh->query($sql) as $row) {
echo '$row[\'Location\'] is: ' . $row['Location'] .'<br />';
$this->termLocs[] = $row['Location'];
}

Categories