I've been playing around with this one for a few days, I'm not a professional coder but I'm trying to put a nice basic system in place to manage checkin/out at a local volunteer rescue organization.
Basically I'm trying to get all members member with the ISLOGGEDIN value set as 1
$loggedin = mysql_query("SELECT * FROM members WHERE ISLOGGEDIN=1");
$loggedinarray=mysql_fetch_array($loggedin);
And present their information (name, etc) into a table:
foreach($loggedinarray as $key=>$value) {
echo "
<tr>
<td>".$value[firstname]." ".$value[lastname]."</td>
<td>".$value[timeloggedin]."</td>
</tr>
";
}
However the results I'm getting are quite random and not what I'm looking for, at all!
var_dump($loggedinarray) output:
array(12) { [0]=> string(5) "5395" ["SES_ID"]=> string(5) "5395" [1]=> string(7) "Anthony" ["FIRST"]=> string(7) "Anthony" [2]=> string(8) "LastName" ["LAST"]=> string(8) "Willison" [3]=> string(1) "1" ["ISLOGGEDIN"]=> string(1) "1" [4]=> string(1) "0" ["TRAINER"]=> string(1) "0" [5]=> string(1) "1" ["OFFICER"]=> string(1) "1" }
Any help would be greatly appreciated!
You have to use while; it was random, because it fetched only one row from table.
$loggedin = mysql_query("SELECT * FROM members WHERE ISLOGGEDIN = 1");
if (mysql_num_rows($loggedin) > 0) {
echo "<table>";
while ($row = mysql_fetch_array($loggedin)) {
echo "
<tr>
<td>".$row['FIRST']." ".$row['LAST']."</td>
<td>".$row['timeloggedin']."</td>
</tr>
";
}
echo "</table>";
}
This code will output every row from table, where ISLOGGEDIN = 1.
PS: about data $row['timeloggedin'], you dont have it in your query (as seen in var_dump), so it will be an empty string.
Related
First of all, I couldn't think of any better title, sorry if you find it inapropiate.
I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.
The first database accounting has
subscriber_id | amount | zone_id
stored in the table named cdr
The second db billing has stored inside the table billing_zones these values:
zone_id | zone_name
Everything I've done works fine, but the resulting array is not what I expected/wanted.
This is my code:
try {
$conn = new PDO('mysql:host=host;dbname=accounting','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
FROM `billing`.billing_zones a INNER JOIN cdr b
ON a.`id` = b.`source_customer_billing_zone_id`
WHERE destination_account_id = :destinationId
GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));
foreach ($stmt as $row) {
$data[] = $row;
}
for ($i=0; $i < sizeof($data); $i++) {
$sanitizedData[$i] = array(
0 => $data[$i][0],
1 => $data[$i][1],
2 => $data[$i][2]
);
}
/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
$newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
}
}
var_dump($sanitizedData);
The result of the code above my ATTEMPT comment is a big array, I will show you a piece of it so you can understand better what I want to do:
[1047]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "V30048086"
[2]=>
string(10) "460.440000"
}
[1048]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 902 Nivel 1"
[1]=>
string(9) "V30048086"
[2]=>
string(9) "87.301236"
}
[1049]=>
array(3) {
[0]=>
string(25) "Llamadas Fijos nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "64.340367"
}
[1050]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(10) "116.480000"
}
[1051]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "62.559759"
}
To clarify:
array[n][0] is the aforementioned zone_name
array[n][1] is the subscriber_id - The id defining the customer
array[n][2] is the SUM() of the amount for that id in that zone.
So the result is that for every id, there are several arrays for each zone.
What I want to do is to group those in a unique array like:
[1051]=>
array(3) {
[0]=>
string(9) "W24154073"
[1]=>
string(28) "Llamadas Premium 901 Nivel 1"
[2]=>
string(9) "62.559759"
[3]=>
string(28) "Llamadas Moviles nacionales"
[4]=>
string(9) "116.480000"
[5]=>
string(28) "Llamadas Fijos nacionales"
[6]=>
string(9) "64.340367"
.
.
.
If there were more
}
As #Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:
["W24154073"]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "62.559759"
[2]=>
string(28) "Llamadas Moviles nacionales"
[3]=>
string(9) "116.480000"
[4]=>
string(28) "Llamadas Fijos nacionales"
[5]=>
string(9) "64.340367"
.
.
.
If there were more
}
This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.
I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.
If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.
Thank you for the help, have a great weekend!
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.
This can be a achieved in quite a simple fashion, like this:
$data = [];
foreach ($stmt as $row) {
// $row[1] is the subscriber_id
$data[$row[1]][] = $row[0]; // $row[0] is zone_name
$data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);
The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.
I have a little question.
I have few stored values in session Array. These values are ID's of products.
After that i want to display products from my database, but this is not working propertly for me.
Can someone help me a little? :) (I am still learning :) )
<?php
include 'includes/dbconnect.php';
$orderid = $_SESSION['order'];
foreach ($orderid as $value) {
$sql="SELECT * FROM product WHERE productID LIKE '%$value%'";
$result=$conn->query($sql);
while($row=$result->fetch_assoc()){
echo '<tr>';
echo '<td>'.$row["tag"].'</td>';
echo '<td>'.$row["price"].',- Kč</td>';
echo '<td><img src="images/'.$row["tag"].'.jpg" width=70"></td>';
echo '<td>1</td>' ;
echo '<td>X</td>';
}
}
?>
var_dump($orderid); shows:
array(1) {
["order"]=> array(10) {
[0]=> string(2) "44"
[1]=> string(2) "46"
[2]=> string(2) "44"
[3]=> string(2) "54"
[4]=> string(1) "1"
[5]=> string(2) "44"
[6]=> string(1) "1"
[7]=> string(2) "44"
[8]=> string(2) "47"
[9]=> string(2) "74"
}
}
Just for the purposes of SO, I'll make my comment as an answer:
In the $sql query instead of using LIKE '%$value%'"; use this: LIKE '". $value ."'";
This ensures that we actually get the value of the variable.
Im trying to setup a dynamic settings database for my CMS
Database is set up with two columns.
Name | Value
Template | Exige
InstallFolder | v2
Basically I want to pull all the data out and put it into different variables.
for example i'm trying to set my base_folder(installation folder) into a variable.
So say $base_folder = $CoreSettings[1] output which should show (v2)
$sql = "SELECT * FROM core_settings";
$query = mysqli_query($dbc, $sql) or die (mysqli_error($dbc));
$CoreSettings = array();
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$CoreSettings[] = $row;
}
$base_folder = $CoreSettings;
foreach( $CoreSettings as $key => $val)
{ $$key = $val; }
var_dump($base_folder);
This then outputs:
array(5) { [0]=> array(2) { ["name"]=> string(8) "Template" ["value"]=> string(5) "exige" } [1]=> array(2) { ["name"]=> string(13) "InstallFolder" ["value"]=> string(2) "v2" } [2]=> array(2) { ["name"]=> string(16) "MaintainanceMode" ["value"]=> string(1) "0" } [3]=> array(2) { ["name"]=> string(4) "Logo" ["value"]=> string(8) "Logo.png" } [4]=> array(2) { ["name"]=> string(8) "SiteName" ["value"]=> string(18) "Black Nova Designs" } }
I would like to just get the InstallFolder Value.
so
$base_folder = V2
Sorry if this comes across stupid just really racked my brain about, and code is probably quite messed up due to trying multiple methods.
But in the long run I would like to get every setting out of the database and be able to assign a variable to each setting.
for example
$SiteName = $CoreSettings[4];
$maintenance = $CoreSettings[2];
Thanks In advanced.
Kyle
Index you $CoreSettings array with the values of the 1st column, then you can access the values by the appropriate key:
$CoreSettings = array();
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$CoreSettings[$row['name']] = $row['value'];
}
echo $CoreSettings['InstallFolder']; //outputs V2
echo $CoreSettings['Template']; //outputs Exige
This is for a recipe project where users use a form and enter their own recipes. I have that whole part working. Now I'm trying to retrieve the recipe's information from the database and display it on a page. Anyway, this is the code I have right now.
<?php
include_once('includes/connection.php');
include_once('includes/recipe.php');
$recipe = new Recipe;
if (isset($_GET['id'])) {
$id = $_GET['id'];
$basic_data = $recipe->fetch_data($id);
$sql1 = $pdo->prepare("SELECT recipes.*, categories.* FROM recipes
INNER JOIN categories
ON (recipes.category_ID = categories.category_ID)
WHERE recipes.recipe_id = ?");
$sql1->bindValue(1, $id);
$sql1->execute();
$results1 = $sql1->execute();
echo $results1 = $sql1->fetchAll(PDO::FETCH_ASSOC);
var_dump($results1);
?>
This is what I see on my webpage when this code runs. I've never worked with associative arrays before, so I'm really lost as to how I can echo specific data contained in one. For the purpose of this question, I'm focusing on the "category_name" and I'm trying to echo just the value stored in the "category_name" for this recipe, which happens to be "none". How do I echo just the word "none" to the page?
Arrayarray(1) {
[0]=> array(15) {
["recipe_ID"]=> string(1) "1"
["recipe_name"]=> string(20) "English Muffin Pizza"
["category_ID"]=> string(1) "1"
["servings_ID"]=> string(2) "13"
["prep_hours"]=> string(1) "0"
["prep_minutes"]=> string(2) "20"
["cook_hours"]=> string(1) "0"
["cook_minutes"]=> string(2) "10"
["oven_temp"]=> string(3) "350"
["directions"]=> string(402) "These are the directions."
["extra_comments"]=> string(37) "This is a short extra comment."
["recipe_favorite"]=> string(1) "1"
["recipe_photo"]=> string(0) ""
["created"]=> string(19) "2014-09-20 10:22:39"
["category_name"]=> string(4) "none" }
}
Please let me know if I can give you any more information. It's been a long day and I may be missing something that could help you to help me.
If you are strictly trying to echo category_name in this array you would just write:
echo $results1[0]['category_name'];
You need to use a loop to go through $results. That will echo category_name for all recipes.
foreach ($results1 as $recipe) {
echo $recipe['category_name'];
}
If you know you want the recipe at key 0 (first recipe), you can simply do:
echo $results[0]['category_name'];
I'll start with the problem. I'm looping through mysql_fetch_assoc() calls to display all fields from a row. Every new pass gives me the new row PLUS the old row values as well. It compounds each pass. I've tried many things and looked through many posts and forums and haven't quite found what I need to fix it. Any help is appreciated.
edit: Sorry but the indentation gets messed up after I post the question.
Here's the MySQL table script:
CREATE TABLE pay_hours
(
_key int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
_userNumber int(11),
_hoursWorked double
);
CREATE TABLE pay_dates
(
_key int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
_userNumber int(11),
_dateWorked date
);
Here's the query:
$query = "SELECT h._userNumber, d._dateWorked, h._hoursWorked FROM pay_hours h, pay_dates d WHERE d._userNumber=h._userNumber ORDER BY d._dateWorked DESC"; // gets the user, hours and dates and displys most recent dates first.
$result = $keyFrameObject->Execute($query); // wrapper for mysql_query()
Here's the loop:
$row = mysql_fetch_assoc($result);
while ($row)
{
$table .= "<tr>";
foreach ($row as $field)
{
$table .= "<td>" . $field . "</td>";
}
$table .= "</tr>";
$row = mysql_fetch_assoc($result);
}
It's a PHP page and I will eventually echo a table created with this data. I'm entering values for dateWorked and hoursWorked while using the same userNumber value for testing purposes. Here's some sample input and output (using var_dump($row) ):
input:
date = 2011-08-05
hours = 1
output:
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" }
Now the page has posted back and I'll enter in a new set of values:
input:
date = 2011-08-04
hours = 5
output (unformatted):
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "5" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "1" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "5" }
output (formatted):
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "5" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "1" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "5" }
Every time I enter in values and run through the code, it compounds further. I believe the issue is the loop but I'm not sure. Somehow $row is maintaining value after a post back.
Thanks again for the help and let me know if any more info is needed.
Change $table .= ""; to $table = "";
The .= is preserving the values of $table from the previous loops.
Problem solved. The answer is in the comments below. Thanks for the help.
I've figured it out. Because of the design of the tables, it would insert twice which would cause compounding. I changed everything into a single table and the ambiguity disappeared. Thanks for all of your help. I'm not sure how to mark this as solved, but if the mods are watching, could you help a brother out? – Matt 9 hours ago