Is it okay use the same variable name on PHP while? - php

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.

Related

Finding the differences between two rows of data, key by key

I have two rows of data - always just two rows, but there could be a maximum of around forty columns. The column names are different on a case by case basis, but here is a representative example:
id | height | width | colour | in_stock | featured | on_sale
------------------------------------------------------------
1 | 30 | 20 | black | yes | no | yes
2 | 30 | 25 | red | yes | yes | no
I want to get all of the differences between those two rows into an array so that I can log what was changed from row 1 to row 2.
I thought it array_diff() would do the job!
So I cheerfully chucked array_diff() at it thus:
//Simplified queries for the example
$sql1 = "SELECT * FROM table WHERE id = 1";
$rs1 = $conn->Execute($sql1);
$rs1 = $rs1->fields;
$sql2 = "SELECT * FROM table WHERE id = 2";
$rs2 = $conn->Execute($sql2);
$rs2 = $rs2->fields;
//Build first array
foreach($rs1 as $key => $value){
$data1[$key] = $value;
}
//Build second array
foreach($rs2 as $key => $value){
$data2[$key] = $value;
}
//Find the differences
$theDifferences = array_diff($data1, $data2);
//Loop through the differences logging the changes
foreach($theDifferences as $field => $value){
echo "Change found for ".$field."!";
}
Why that doesn't work.
This "looked like" it was working. Since many columns contain long strings, colour names, dates etc, so when one changed it was duly pushed into the differences array. The problem was (of course) that the multiple "yes" or "no" columns did not behave as I had expected. Thus the result of the code above, for the table example is:
colour, width
It is not "seeing" the featured or on_sale columns as changed because the data1 array AND the data2 array both contain no's and yes's.
I suppose I need to compare on a key by key basis? Something like the opposite of array_diff_key()? But here I am stuck.
I also considered if this could be done solely with the SQL query, which would I suppose be more efficient, but that is way beyond my SQL ability.
Thanks in advance.
I think you're very nearly there. Maybe something like this after your queries:
$theDifferences = array();
foreach($rs1 as $key => $value){
if ($rs2[$key] != $value){
$theDifferences[$key] = $value;
}
}
As for SQL, you can use an EXCEPT to get a list of rows which are different between two queries, but you'd still have to loop through the keys and look for nulls - which doesn't save you a whole lot.

returning MySQL cell value based on calculated value between other columns in the table

I have a MySQL Table which is structured like so:
key ID value1 value2
| 1 | | ID1 | |2| |4|
| 2 | | ID2 | |5| |5|
.
.
.
I need to query this table and return just the IDs based on ascending order of the difference between value1 and value 2. If there are equal values then the ID order is irrelevant and can be random. The format of the output is important though. It should be a long string separated by the shown tokenizer. I have:
$query = "Select * From `Table`";
$result = $conn->query($query),
while($row = $result->fetch_assoc()) {
code???
echo $row["ID"]."!##$";
}
How can I structure the missing code block to accomplish this? I think what I want to do is create a variable which is (value1 - value2) then create an array which stores the id as a key with the result and sort ascending then echo the key. I just don't know how to write it
Have a look at this - PHP MySQL Multi Query

How can I get the sums of all the integers in a row of an SQL table with PHP?

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;

Creat treeview array or sub array

These are the data as they are in mysql table
Table A (Tasks)
task_id | name | description
-----------------------------
1 | soccer| fora
-----------------------------
2 | sussam| forb
-----------------------------
3 | sosssi| forc
-----------------------------
4 | sillly| ford
Tabble B Milestones
mile_id | name | task_id
------------------
1 | task1mi | 1
------------------
2 | task2mi | 1
-------------------
3 | task3mi | 3
I am looking to making a treeview array, something like for each task as a parent milestone as a child array of task id.
What the print_r() function should return (desired output with php after mysql query)
array(
name=>'soccer',
description =>'fora'
task_id=>array(
mile_id=>'1',
name=>'task1mi'
)
)
Any Suggestions
You can do it following way but it is not good for performance. I don`t know exact requirement and fretwork are you using. So i am giving basic idea.
$sqlparent = "select * from tasks";// get your task details from database.
$parentData = $sqlparent;// result from sql function.
foreach($parentData as $key=>$value)
{
$sql = "select * from Milestones where task_id='".$value['task_id']."'";// find the Milestones of the task
$milestonesResult = mysql_featch_array($sql); // run sql and get data from database it is giving you single record you need to create loop here. as i don`t know what are you using for PHP.
$value['milestoneslist'] = $milestonesResult; //task_id=>array( here you can not use task_id => array as it is already there. if you do it it will over-right the task_id
}
I hope you will get idea from this.
You can use below code for your solution as i thought
$sql = "select table_b.*,table_a.name as aname, table_a.description as description as aname from table_b left join table_a on table_b.task_id=table_a.task_id"
$result = mysql_query($sql);
//based on above query result you will get array on mysql_fatch_assoc
$result_array = array();
while($result = mysql_fatch_assoc($result)){
$tmp_arr = array();
$tmp_arr['mile_id'] = $result['mile_id'];
$tmp_arr['name'] = $result['name'];
$result_array[$result['task_id']]['name'] = $result['aname'];
$result_array[$result['task_id']]['description'] = $result['description'];
$result_array[$result['task_id']]['task_id'][] = $tmp_arr;
}
$result_array = array_values($result_array);
print_r($result_array);

retrieve information from multiple rows with php after query-ing

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

Categories