Ok, this is the last part I'm having trouble with in this project (my first php/mysql attempt). The trouble comes in the last 'while' loop. I haven't been able to find a way of assigning values to my array of variables. While when working with one row in the table this format works to get multiple columns, I am looking for a way to get one field from multiple (3) rows. Thoughts?
$x=1;
do{
$sql = "SELECT * FROM`".$tableName."` WHERE `StopId`=".$stopId." AND `Time` >='". $time. "' LIMIT 3";
$result = mysql_query($sql, $conn);
if (!$result){
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
This is the part that is causing me the trouble. It assigns the last result (because it's limited to 3 results) to all of the values. If I change the limit to 1 or 2, it makes all the values either the first or second results. I want the first one in time1, the second one in time2 and the third in time3.
while ($row = mysql_fetch_array($result)) {
$time1[$routeName[$x]] = $row[Time];
$time2[$routeName[$x]] = $row[Time];
$time3[$routeName[$x]] = $row[Time];
}
$x++;
}while(!is_Null($routeName[$x]));
EDIT:
The table is in the format:
| IdNum | StopId | Time |
| 1 | 1 | 12:44 |
| 2 | 2 | 13:15 |
| 3 | 1 | 12:55 |
| 4 | 2 | 14:15 |
| 5 | 1 | 13:20 |
and so on. If I was to have $stopId = 1 and $time = 12:30 I would want to be able to assign:
"12:44" to $time1[$routeName[$x]]
"12:55" to $time2[$routeName[$x]]
"13:20" to $time3[$routeName[$x]]
Also I should add that the query statement is functional.
Edit:
Sorry about that I changed $routeNum to $routeName after the original posting to help clarify what the variable contained. It's just a string title that forms part of the table name.
Well you are looping over only one row at a time remember. So, if you set all three variables at once, they are all going to be the values of the last row. I don't know where your $routeName variable is coming from?? try:
$x = 0;
while ($row = mysql_fetch_array($result)) {
$routeName[$x] = $row['Time'];
$x++;
}
I don't know how you want to format it? If you must have it formatted into separate variables instead of an array, I think you can do this, however I don't know why you would want to format it like that.
$x = 0;
while ($row = mysql_fetch_array($result)) {
${time.$x[$routeName[$x]]} = $row['Time'];
$x++;
}
If you
Related
I just wondering is it okay if I use the following code :
$query = mysqli_query($db, "SELECT * FROM myTable1")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id'];
}
Then I fetch another table like this :
$query = mysqli_query($db, "SELECT * FROM myTable2")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id'];
}
I use the same variable $result and $temp.
I mean is it okay to use such code ? Should I named the variable differently like $result1 $result2 and so on ?
Let's say, which one is better, safer, between use the same variable name or give the variables different name ?
I hope someone could explain about it.
Thank you before.
If you follow SOLID principle, especially the single responsibility principle wants you to isolate functionality into different function.
If you do apply this, then you are not really using the same variables, because at that point there would be in different scope, therefore it would not be an issue.
In short you shouldn't have to reuse variables, if your logic is broken up into function that perform a single task, please do not name them $result1, result2 etc ... this is a sign of code smell in your project.
If you are done with myTable1 then it is totally ok but if you are going to use it somewhere else in code then no because only myTable2 information will be saved in $result
if you use same variable to store your data then every iteration the variable value will be override with new value, and the value after while statement is the last iteration.
$temp is a local variable to the while if you haven't defined it before so it is safe to be used like that.
$query, from what the language lets you do, yes you can use it this way.
Basic PHP code
Let's say you want to store some information from database into variable and then use it before doing some more coding.
So we have this sample code. Storing id value into $temp variable. What is the output we get?
$query = mysqli_query($db, "SELECT * FROM myTable1")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id'];
}
For example table myTable1 contains data like this.
+----+---------+---------+
| id | Col1 | Col2 |
+----+---------+---------+
| 1 | Value 1 | Value 2 |
| 2 | Value 1 | Value 2 |
| 3 | Value 1 | Value 2 |
| 4 | Value 1 | Value 2 |
+----+---------+---------+
Our $temp variable will be equal to 4. Because you are getting everything from that table and then fetching every result that comes up. Now, let's use that variable.
echo 'Selected id from table myTable1 equals ' . $temp;
Which results in
Selected id from table myTable1 equals 4
Then, we are getting data from another table called myTable2.
$query = mysqli_query($db, "SELECT * FROM myTable2")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id'];
}
That table contains data like this.
+----+---------+---------+
| id | Col1 | Col2 |
+----+---------+---------+
| 3 | Value 1 | Value 2 |
| 5 | Value 1 | Value 2 |
| 6 | Value 1 | Value 2 |
| 8 | Value 1 | Value 2 |
+----+---------+---------+
Again, same thing happens, $temp variable is now equal to 8. Let's use it same way.
echo 'Selected id from table myTable2 equals ' . $temp;
Which results in
Selected id from table myTable2 equals 8
Final result
Selected id from table myTable1 equals 4
Selected id from table myTable2 equals 8
Conclusion
Nothing wrong here. You can do that if you want. But be aware that it's not recommended to use variable with same name multiple times if you have way more lines of code.
More complex PHP code
Same tables, structure and data. Let's change code.
function printIndex($id) {
echo 'Index = ' . $id;
}
$query = mysqli_query($db, "SELECT * FROM myTable1")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id']; // Store id for further use
}
$query = mysqli_query($db, "SELECT * FROM myTable2")
while($result = mysqli_fetch_assoc($query)){
$temp = $result['id']; // Store id for further use
}
printIndex($temp); // Print stored id
Output
Index = 8
Conclusion
Bad coding. You have to use unique variable names to prevent such situation.
You can use the same variable names logically. It won't give you an error(sometimes it might if you use these variables out of your loop in this context). But using general keywords for variable names are not advisable.
Instead try to name the variables based on your Model. Please look at the below examples,
If your 'myTable1' about students then you can use $student instead of $result1.
Again, if your 'myTable2' is about products then you can use $product instead of $result2.
I am currently making an attendance website. The data for attendance is stored like this...
+-----------------------------------------------+
| Name | 12/20/16 | 12/21/16 | 12/23/16 |
+-----------------------------------------------+
|Person1 | 1 | 0 | 1 |
|Person2 | 0 | 1 | 0 |
|Person3 | 1 | 1 | 1 |
+-----------------------------------------------+
If a person was there, then the date column for their row is marked as a "1". If they weren't there, then the date column for their row is marked as a "0".
I am trying to make a readout of how many days they were present.
How can I get a sum of all the values in the date columns for that specific person's row in PHP?
EDIT: I understand that it is a bad way of formatting the data. This is per the owners request. They have their mind set on it and won't listen to reason. They are thinking of SQL as an Excel file.
Since you can't refactor the database to work the only way to do this is
SELECT name, `12/20/16`+`12/21/16`+`12/23/16` as days_attended
FROM tablename
and yes every time you add a column you have to change your query.
You could make a dynamic query -- use the above as a template as to what that dynamic query would look like.
But you REALLY should refactor the database and make a view for your user to make them happy.
This is exactly why views exist.
Okay so with the help of some people in the comments, I have put together a working function to accomplish what I needed.
$ppl = mysqli_query($conn, "SELECT * FROM Attendance2016 WHERE name = '" . getSessionVal("Name") . "'");
$row = mysqli_fetch_array($ppl);
$loopMax = count($row);
$currentAtttendance = 0;
for($x = 0; $x < $loopMax; $x++){
if($row[$x] === "0"){
continue;
}else if($row[$x] === "1"){
$currentAtttendance = $currentAtttendance + 1;
}
}
return $currentAtttendance;
Let's assume I have a table like this:
+------+---------+--------------+-------------+---------------+
| id | tstamp | product_id | name | configuration |
+------+---------+--------------+-------------+---------------+
| 3 | 15 | 02 | bike | abc |
| 2 | 16 | 03 | car | dfg |
| 1 | 11 | 04 | tree | ehg |
+------+---------+--------------+-------------+---------------+
When I run a simple query like
SELECT id, tstamp, product_id, name, configuration
FROM tl_iso_product_collection_item
ORDER BY `id` DESC
It returns 3 rows. As expected. Works, right? BUT, if I implement this query into a PHP script and try to fetch rows, theres always ONE missing. Always. Even in the most simple query. Where did I make a mistake?
Script looks like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$connection = mysqli_connect('localhost', 'user', 'pw', 'db');
mysqli_set_charset($connection,"utf8");
$query = "SELECT id, tstamp, product_id, name, configuration
FROM table
ORDER BY `id` DESC "
$result = mysqli_query($connection, $query);
while ($row=mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
}
mysqli_close($connection);
?>
This will result in displaying only 2 out of 3 rows. My question is, why tho? If I insert the query above directly into phpmyadmin it shows 3 results, not 2. What is wrong here? Am I missing something? Thanks in advance.
$fetch_allgemein = mysqli_fetch_array($result_allgemein);
$fetch_configuration = mysqli_fetch_array($result_configuration);
You are fetching the first record for each query result here already – so the internal “pointer” to the current record gets advanced to the second record in each result set, and therefor when you loop over the result using
while ($row=mysqli_fetch_row($result_allgemein)) {
later on, the first record is of course omitted.
You will need to reset the “pointer” using mysqli_result::data_seek if you want to get all records in your loops after you’ve already fetched the first record each.
I have a while loop which separates all the linked numbers into different sections in a table. Here is the statement:
$result2 = mysqli_query($con,"SELECT a.*, b.*, c.* FROM b_statement_main a
INNER JOIN b_crm_company b ON a.COMPANY_ID = b.ID INNER JOIN b_statement c
ON a.LINK = c.LINK
WHERE a.COMPANY_ID = '$companyID2' AND a.COMMENCE BETWEEN '$from2' AND '$to2' ");
$linked = -1;
while($row = mysqli_fetch_array($result2))
{
$companyName = $row['TITLE'];
$arDates = strtotime($row['COMMENCE']);
$remaining = $row['REMAINING_HOURS'];
$linking = $row['LINK'];
$arNumber = $row['REF_NUMBER'];
$billable = $row['BILLABLE'];
if($linked != $row['LINK'])
{
print "<tr><td><strong>$companyName</strong></td><td></td><td><strong>".date('d/m/Y',$arDates)."</strong></td><td></td><td></td><td><strong>$remaining</strong></td></tr>";
$linked = $row['LINK'];
}
print "<tr><td></td><td></td><td></td><td>$arNumber</td><td>$billable</td><td></td></tr>";
}
print "</table>";
So what this returns is a title for each section and then it loops the results related to the query below. Once it has returned all the respective results it will then display the title section again and loop the related results again. It will repeat this until everything has been displayed.
However what I wanting is for the title section to be below the looping results. So, therefore it will loop the results and then once it has looped them all for that particular section, put the title underneath. It will then go in and loop the results again and put the title underneath and it will carry on until it is completed.
Anybody have any idea how I can do this. Obviously if I move the print before the if, then it puts the result, title, result, title etc.
So this is what it looks like at the moment (not accurate but just to show the title and the results):
| Company | Date | Hours |
| Title 1 | 20/11/2014 | |
| Result 1 | 10/11/2014 | 44 |
| Result 2 | 08/11/2014 | 22 |
When I need it like:
| Company | Date | Hours |
| Result 1 | 10/11/2014 | 44 |
| Result 2 | 08/11/2014 | 22 |
| Title 1 | 20/11/2014 | |
How about creating a new array based upon the entries you want in the table. So your code would go something like (note $outputarray was added):
Edit: This assumes there is only one Title per data set. If you want more than one title per set of records, you need to set something in the record that identifies a set. In this case, the easiest way was to make a multi-dimension array of the results, based upon if it was a title or not (by your criteria).
$linked = -1;
while($row = mysqli_fetch_array($result2)){
$companyName = $row['TITLE'];
$arDates = strtotime($row['COMMENCE']);
$remaining = $row['REMAINING_HOURS'];
$linking = $row['LINK'];
$arNumber = $row['REF_NUMBER'];
$billable = $row['BILLABLE'];
if($linked != $row['LINK']){
$outputarray['title'][] ="<tr><td><strong>$companyName</strong></td>
<td></td><td><strong>".date('d/m/Y',$arDates)."</strong></td><td></td><td>
</td><td><strong>$remaining</strong></td></tr>";
$linked = $row['LINK'];
} else {
$outputarray['row'][]= "<tr><td></td><td></td><td></td><td>$arNumber</td>
<td>$billable</td><td></td></tr>";
}
}
print"<table>
<thead>"; // etc... have the titles go here.
foreach($outputarray as $key=> $value){
if($key=='title'){
$thistitle=$value;
} else {
print $value;
}
}
print $thistitle;
print "</table>";
I have a simple my-sql table:
+----+----------+----------+-------------+-----------+
| id | Name | Father | National | Value |
+----+----------+----------+-------------+-----------+
| 1 | Daniel | David | American | 0 |
| 2 | Rebbeka | Craig | American | 0 |
| 3 | Robert | John | American | 0 |
| 4 | Arjun | Daneil | Indian | 0 |
| 5 | Ana | Peter | British | 0 |
+----+----------+----------+-------------+-----------+
I need to a php-script to query and fetch new single row every time it is executed. It may be based on ID.
About code/framework, i am using simple php5 with mysql on ubuntu server.
This is my code, the probelem is that it outputs whole of the Name,Father columns every time on call, i just want to print a single row everytime it is executed. and on every php script execution a new row should be printed based on id in ascending order.
<?php
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table");
while($row = mysqli_fetch_array($result)) {
echo "Name:" . $row['name'] . " " . "Father's Name:" . $row['father'];
echo "<br>";
}
mysqli_close($con);
?>
Every help is much appreciated.
the below code will help you get the output.
from next time when you ask any question pls add your code.
$link = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM `emp` ORDER BY RAND() LIMIT 0,1;" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
//display information:
$row = mysqli_fetch_array($result);
echo $row["name"].$row["Father"].$row["National"].$row["Value"];
As i have no much details of what type of code/framework you have I am giving you a answer on the basis of what I understand
There will be two ways I can think of to fetch the data
1.
Change the Table Structure and add one more column called lastFetched and every-time you fetch the row update the particular row by 1 and else everything else to 0 so that next time when you fetch the row you already know which is the last row fetched by you. and you can do an increment to it.
2.
On the page you are fetching the result would have a hidden input where you can store the last data number letz say first time it is 0 when page loads
then your query will be
SELECT * from <tablename> LIMIT 0,1
and increase the value of the hidden input to +1
so next time you fetch the result will gives the query
SELECT * from <tablename> LIMIT 1,2
From the discussion we had in the comments I came to a conclusion that you are looking for this.
<table>
<tr>
<?php
if(isset($_POST['pullNextRecord'))
{
$whtrec=$_POST['whatrecord'];
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table LIMIT $whtrec, ++$whtrec");
echo "<input type='hidden' name='whatrecord' value=".$whtrec." />";
echo "<th>Name</th><th>Fathers Name</th></tr><tr>";
while($row = mysqli_fetch_array($result))
{
echo "<td>$row['name']</td><td>$row['father']</td>";
}
mysqli_close($con);
}
?>
<input type="submit" name="pullNextRecord" />