Pulling All Associated Rows MySQLi - php

I have to pull from a table that's been made by someone else and print it onto a web page. Issue is, that column name are stored in the rows. For instance:
FIELD_NAME| FIELD_VALUE
______________________
first-name| John
last-name | Smith
This is how I'm going about grabbing the data
$tableRow = '';
$sql ="SELECT * FROM `wp_cf7dbplugin_submits` WHERE form_name = '".$nameOfForm."' ";
$result = $mysqli->query($sql);
while($tableData = $result->fetch_assoc()){
$fieldName = $tableData['field_name'];
$fieldValue = $tableData['field_value'];
//FIRST NAME
if($fieldName == 'first-name'){
$firstName = $fieldValue;
}
//LAST NAME
if($fieldName == 'last-name'){
$lastName = $fieldValue;
}
//BUILD A ROW FOR THE TABLE
$tableRow .='
<th>'.$firstName.'</th>
<th>'.$lastName.'</th>
';
}
it only KIND of works when I do $tableRow = instead of $tableRow .=
it will only show me one result, but when I do $tableRow .= it will only show me empty but the correct amount of s.
How can I populate an html table with all of the results pulling from a table like this?
EDIT:
I forgot to mention that the whole table looks like this:
<table id="theTable">
<thead>
<tr>
<th style="width:100px;">First Name</th>
<th style="width:100px;">Last Name</th>
</tr>
</thead>
<tbody id="rowsGoHere">
</tbody>
</table>
and I echo the PHP result via ajax,
//ECHO BACK RESULTS
$JSONData = array("true", $tableRow);
echo $_GET['callback']."(".json_encode($JSONData).")";
and use this to insert into table
var trueEncV = encodeURIComponent("true");
$.getJSON("pullTableData.php?callback=?",
{
trueV: trueEncV
},
function(dataBack){
alert(dataBack);
$('#rowsGoHere').html(dataBack[1]);
}
)
That all works fine and dandy.

According to your updated code the <tr> tags are missing. Also, within <tbody> you should use the <td> tag instead of the <th> tag.
$tableRow .='
<tr>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
</tr>
';
Can you try
echo json_encode($JSONData);
instead of
echo $_GET['callback']."(".json_encode($JSONData).")";

Related

The row doesn't get DELETED in MySQL and PHP returns no error

I have a code which should delete a selected ID row from table by loading a remove.php file with SQL query. The problem is that it doesn't work but I get no errors or notices. My variable seems to get transfered to remove.php in URL just fine, as '<a href="remove.php?='.$Fvalue.'">' gets interpreted as
remove.php?=1
for example, where 1 is primary id of the row.
Here is all the code related to the question only:
EDIT:
Rendered HTML for products table with REMOVE button:
<!-- Products table -->
<table class="table">
<thead>
<tr>
<th scope='col'>id </br ></th><th scope='col'>name </br ></th><th scope='col'>price </br ></th><th scope='col'>amount </br ></th><th scope='col'>category_name </br ></th> </tr>
</thead>
<tbody>
<tr><td data-id="1"> REMOVE</td>
<td>iPhone 7</td>
<td>800</td>
<td>15</td>
<td>Smartphones</td>
</tr><tr>
<td data-id="42"> REMOVE</td>
<td>Motorola </td>
<td>3000</td>
<td>5</td>
<td>Smartphones</td>
</tr><tr><td data-id="2"> REMOVE</td><td>Macbook Pro 2015</td>
<td>1300</td><td>10</td>
<td>Computers</td></tr><tr><td data-id="4"> REMOVE</td>
<td>Dell XPS</td>
<td>1400</td>
<td>6</td><td>Computers</td>
</tr><tr><td data-id="41"> REMOVE</td>
<td>CHROMEBOOK</td>
<td>5600</td>
<td>8</td>
<td>Computers</td></tr></tbody>
Updated PHP:
<?php
foreach ($newArray as $value) {
echo '<tr>';
foreach ($value as $key => $Fvalue) {
$remove = $value['id'] = " REMOVE";
if($value[$key] == $value['id']) {
echo '<td data-id="'.$Fvalue.'">' . '' . $remove . '' . '</td>'; // will show all values.
} else {
echo '<td>' . $Fvalue . '</td>';
}
}
echo '</tr>';
}
?>
remove.php
<?php
require_once ("navigation.php");
require_once("database_connection.php");
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id != null) {
$deleteProducts = "DELETE FROM `products` WHERE `id` = '.$id.'";
mysqli_query($dbc, $deleteProducts);
}
Looking for any help to me spot any problems as I get no errors and have no idea why the code is not deleting a row in the table. Thanks.
You have to pass a key associated with the value you are sending;
' . $remove . '
Notice the remove_id part.
Now, in your PHP you can retreive this value;
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id !== null) {
$deleteProducts = "DELETE FROM `products` WHERE `id`='{$id}'";
mysqli_query($dbc, $deleteProducts);
}
In my code here, I also fixed an issue you had in your code. You had $id = (isset($_GET['$Fvalue']));, which will always set $id to true or false, not to the ID that you had passed.
You can also clean up your HTML variables by using a double quote instead of a single quote.
if($value[$key] == $value['id']) {
echo "<td data-id='{$Fvalue}'><a href='remove.php?remove_id={$Fvalue}'>{$remove}</a></td>"; // will show all values.
} else {
echo "<td>{$Fvalue}</td>";
}
BIG NOTE:
Little Bobby says you may be at risk for SQL Injection Attacks. Learn about Prepared Statements with parameterized queries.
Using the get method, you need key-value pairs in your url.
remove.php?id=1
Where id is the key and 1 is the value.

Horizontal table instead of vertical with PHP

I created a horizontal html table with php using the suggested solution on this post: Printing out a table horizontal instead of vertical using PHP
And my code is like this:
$sql="SELECT Pr1, Pr2, Pr3, Pr4 FROM Tbdata ORDER BY Date DESC";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result);
$Pr1 = '';
$Pr2 = '';
$Pr3 = '';
$Pr4 = '';
while($row = $result->fetch_assoc())
{
$Pr4 .= '<td>'.$row['Pr4'].'</td>';
$Pr3 .= '<td>'.$row['Pr3'].'</td>';
$Pr2 .= '<td>'.$row['Pr2'].'</td>';
$Pr1 .= '<td>'.$row['Pr1'].'</td>';
}
echo '
<table class="table">
<tbody>
<tr>
<td>'.$Pr4.'</td>
</tr>
<tr>
<td>'.$Pr3.'</td>
</tr>
<tr>
<td>'.$Pr2.'</td>
</tr>
<tr>
<td>'.$Pr1.'</td>
</tr>
</tbody>
</table>
';
?>
The code works fine. The only problem is that I extract data with Date DESC in the query. For some reason, the data of the most recent date doesn't appear on the table. What am I missing here? please Thanks.
Every fetch call advances the row count 1 position. Only have the while fetch call. Remove the preceding one (or comment it out, as I have to show).
//$row=mysqli_fetch_assoc($result);
$Pr1 = '';
$Pr2 = '';
$Pr3 = '';
$Pr4 = '';
while($row = $result->fetch_assoc())
You discard the first line...
$sql="SELECT Pr1, Pr2, Pr3, Pr4 FROM Tbdata ORDER BY Date DESC";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result); // Reads row, comment this out
Comment out that last line.
Also as you wrap each item in <td> tags, you don't need them in...
<td>'.$Pr4.'</td>
So remove the <td> and </td> tags in these.

Data table error

Im using a datatable to show records from a DB, using PHP.
See my code below;
<table class="table datatable-basic">
<thead>
<tr>
<th> ID </th>
<th> Name</th>
<th>Address </th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
<?
$result9023=mysql_query("SELECT * FROM hr_locations")or die('ERROR 315' );
$num_rows = mysql_num_rows($result9023);
for ($i = 1; $i <= mysql_num_rows($result9023); $i++) {
$row = mysql_fetch_array($result9023);
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
</tbody>
</table>
The table is showing correctly, with the data populated as it should however I am getting the below error when the page loads.
I have looked at https://datatables.net/tn/4 however it's not making much sense?
Since most MySQL array start with 0 do this:
for ($i = 0; $i < $num_rows; $i++) {
Set $i = 0 then state that $i must be less than the number of rows (if you have 4 you will get 0,1,2,3 (4 rows, properly indexed). Instead of counting the rows again, just use the variable you already set for the count.
You're actually probably doing a little too much with your code. Instead of using an unnecessary for loop, just use a while:
while($row = mysql_fetch_array($result9023)){
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
This way you're making sure to catch each row returned from your query without possibly duplicating or skipping rows as you might do when using a for loop along with mysql_fetch_array() as you're trying to do.

Move to next colum if condition is true when create table with loop in Php

so, what i wanted to do is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
now i am using hard code and the result have to looks like this
so, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
it has to move to next row.
because i am reffering to my db, so i am using loop to create the table, and when i doing that way, i am getting this result....
the result will keep showing until the end in the left side. thats very hard to read for report purposes. so i wanted the result looks like the first figure that i've uploaded.
here is what i am doing now
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
You dont need to declare your trValueTitle in the loop. Plus you need to concatenate it in your echo, try this :
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo"<tr>". $trValueTittle ."</tr>";
}
I don't know what you want to do with the "1", but I think this is what you want to do:
echo "<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
$trValueTittle ="<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<tr>
$trValueTittle
</tr>";
}
echo "</table>";
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>
<thead>
<tr>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo $trValueTittle;
}
echo"</tr>
</thead>
</table>";
#Mantello, good answer, but i think it's better to keep out the "tr" from the loop, cause usually you don't want to place your tableheads (th) in different rows.
#Rax your Code won't work. You'll recive an error. You can't output a Variable the way you did in your echo.
echo"<tr> '.$trValueTittle.' </tr>";
would be fine. But there's also no need to define your variable inside the for loop. This way you slow up your script.

editable table cell using angularJS

Is there a way to show data inside td and allow user to edit it in a way that the change will take place in the sql (MySQL in my case) table?
im creating a table from database using angularJS:
Creating The json file from the table:
$result = mysql_query("select * from `user script settings`");
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user_id'] = $row['user id'];
$row_array['script_id'] = $row['script id'];
$row_array['cron_format'] = $row['cron format'];
$row_array['schedule_last_update'] = $row['schedule last update'];
$row_array['next_execution_time'] = $row['next execution time'];
$row_array['script_exec'] = $row['script_exec'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
showing it in the table:
<table class="table table-bordered table-hover">
<thead>
<td>user name</td>
<td>script name</td>
<td>cron format</td>
<td>schedule last update</td>
<td>next execution time</td>
<td>script exec</td>
</thead>
<tbody>
<tr ng-repeat="x in data">
<td>{{x.user_id}}</td>
<td>{{x.script_id}}</td>
<td>{{x.cron_format}}</td>
<td>{{x.schedule_last_update}}</td>
<td>{{x.next_execution_time}}</td>
<td>{{x.script_exec}}</td>
</tr>
</tbody>
</table>
<script>
function customersController($scope,$http) {
$http.get("getData.php")//test3.php return a json file of users table
.success(function(response) {$scope.data = response;});
}
</script>
I want to allow user to change the cron format value and to update the table ...is there "angularish" way to due that?? if not i'll appreciate guidance for a php solution, thx!

Categories