Incorrect record updating - php

I am trying to update a specific row in a table; however, when the query runs, it updates the last record added instead of the record selected.
The SQL statement was taken straight from phpmyAdmin. I have tried "UPDATE registration_tbl SET Paid = 'PAID' WHERE ID='$row21'" and that still did not work.
Have I put something wrong in the code?
<table class="table table-striped table-hover table table-responsive-sm table-responsive-md table-responsive-lg">
<tr>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
<th>Age</th>
<th>Address Type</th>
<th>Address 1</th>
<th>Address 2</th>
<th>Home</th>
<th>Work</th>
<th>Cell</th>
<th>Email Address</th>
<th>Congregation</th>
<th>RMC</th>
<th>Auxillary</th>
<th>Occupation</th>
<th>Category</th>
<th>Username</th>
<th>Submission Date</th>
<th>Payment Status</th>
<th>Action</th>
</tr>
<?php
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result_set = mysqli_query($conn,"SELECT * FROM registration_tbl");
$num_messages = mysqli_num_rows($result_set);
$num = 0;
while($row = mysqli_fetch_array($result_set))
{
$row1 = $row["Title"];
$row2 = $row["FirstName"];
$row3 = $row["LastName"];
$row4 = $row["Sex"];
$row5 = $row["Age"];
$row6 = $row["AddressType"];
$row7 = $row["Address1"];
$row8 = $row["Address2"];
$row9 = $row["Home"];
$row10 = $row["Work"];
$row11 = $row["Cell"];
$row12 = $row["EmailAdd"];
$row13 = $row["Congregation"];
$row14 = $row["RMC"];
$row15 = $row["Auxillary"];
$row16 = $row["Occupation"];
$row17 = $row["Category"];
$row18 = $row["Username"];
$row19 = $row["DateSubmitted"];
$row20 = $row["Paid"];
$row21 = $row["ID"];
$num++;
echo "<tr>";
echo "<td>$row1</td>";
echo "<td>$row2</td>";
echo "<td>$row3</td>";
echo "<td>$row4</td>";
echo "<td>$row5</td>";
echo "<td>$row6</td>";
echo "<td>$row7</td>";
echo "<td>$row8</td>";
echo "<td>$row9</td>";
echo "<td>$row10</td>";
echo "<td>$row11</td>";
echo "<td>$row12</td>";
echo "<td>$row13</td>";
echo "<td>$row14</td>";
echo "<td>$row15</td>";
echo "<td>$row16</td>";
echo "<td>$row17</td>";
echo "<td>$row18</td>";
echo "<td>$row19</td>";
echo "<td>$row20</td>";
if($row20 != "PAID")
{
echo "<td><input type='submit' class='btn btn-success' name='paid' value='PAID' /></td></tr>";
}
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if(isset($_POST['paid']))
{
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$updatePaymentStmt = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = $row21;";
if(mysqli_query($conn, $updatePaymentStmt))
{
echo "<script>alert('Payment updated successfully!')</script>";
}
else
{
echo "<script>alert('Error in updating Payment!')</script>";
}
}

I think you're going to want a separate form for each row in the table. And you'll need a hidden field in that form containing the ID so the server knows which ID to process when it receives the submission.
Remove any <form>...</form> tags you may have placed to wrap around the whole table, and instead use:
if($row20 != "PAID")
{
echo "<td><form action='' method='post'><input type='submit' class='btn btn-success' name='paid' value='PAID' /><input type='hidden' name='id' value='".$row["ID"]."'/></form></td></tr>";
}
and then
if(isset($_POST['paid']))
{
$id = $_POST["id"];
///etc, you can now use $id in a parameter in your query, to select the correct row
P.S. The rest of the code could also be greatly simplified, as others have mentioned in the comments, and you should definitely fix the SQL injection issue - that's a serious security problem.

This bug comes about from a flaw in your thinking rather than unexpected behaviour in the code.
Effectively you have a while loop that iterates over the entire results set (from the first query) and updates the $row* variables. What this means is that $row21 is always going to be the last selected record. If you were to chuck an ORDER BY id DESC on the end you'd find that the first record was always updated...
So what you actually want to do is add the id into the button - and make each button it's own form - so that when the form is posted the intended id is in the button's value.
Something like:
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$registrations = $mysqli->query($conn,"SELECT * FROM registration_tbl");
$num_messages = $registration->num_rows;
while ($row = $registrations->fetch_assoc() {
echo "<tr>";
echo "<td>{$row["Title"]}</td>";
echo "<td>{$row["FirstName"]}</td>";
echo "<td>{$row["LastName"]}</td>";
echo "<td>{$row["Sex"]}</td>";
echo "<td>{$row["Age"]}</td>";
echo "<td>{$row["AddressType"]}</td>";
echo "<td>{$row["Address1"]}</td>";
echo "<td>{$row["Address2"]}</td>";
echo "<td>{$row["Home"]}</td>";
echo "<td>{$row["Work"]}</td>";
echo "<td>{$row["Cell"]}</td>";
echo "<td>{$row["EmailAdd"]}</td>";
echo "<td>{$row["Congregation"]}</td>";
echo "<td>{$row["RMC"]}</td>";
echo "<td>{$row["Auxillary"]}</td>";
echo "<td>{$row["Occupation"]}</td>";
echo "<td>{$row["Category"]}</td>";
echo "<td>{$row["Username"]}</td>";
echo "<td>{$row["DateSubmitted"]}</td>";
echo "<td>{$row["Paid"]}</td>";
echo $row["Paid"]] !== "PAID" ?
"<td><form method='post'><button class='btn btn-success' name='paid' value='{$row["ID"]}'>Paid</button></form></td>" :
"<td></td>";
}
echo "</tr>";
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if ($_POST['paid'] ?? null) {
$sql = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $_POST["paid"]);
echo $query->execute() ?
"<script>alert('Payment updated successfully!')</script>" :
"<script>alert('Error in updating Payment!')</script>";
}
}

Related

get all values of columns in sql php [duplicate]

I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:
<table border="1">
<tr>
<th>Submission ID</th>
<th>Form ID</th>
<th>IP</th>
<th>Name</th>
<th>E-mail</th>
<th>Message</th>
</tr>
<tr>
<td>123456789</td>
<td>12345</td>
<td>123.555.789</td>
<td>John Johnny</td>
<td>johnny#example.com</td>
<td>This is the message John sent you</td>
</tr>
</table>
And then all the other values below 'john'.
Example taken from W3Schools: PHP Select Data from MySQL
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
It's a good place to learn from!
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);
//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
$all_property[] = $property->name; //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
First, connect to the database:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);
You can use this to display a single record:
For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.
<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>
Or, if you want to list all values that match the criteria in a table:
<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>
Surely a better solution would by dynamic so that it would work for any query without having to know the column names?
If so, try this (obviously the query should match your database):
// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);
// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");
// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);
// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
echo '<td>';
echo $key;
echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
echo '<tr>';
foreach($row as $column) {
echo '<td>';
echo $column;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=#mysql_num_rows($query);
echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";
for($i=0 ,$i<$y,$i++)
{
$values=mysql_field_name($query,$i);
echo "<th>$values</th>";
}
echo "</tr>";
while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
print("<tr>\n".
"<td>$p</td>".
"</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
echo '<table border=1px>'; // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
it would print the table like this
just read line by line so that you can understand it easily..
OOP Style :
At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>

Inserting multiple rows into MySQL with checkbox

Below is my code. I have two MySQL database tables, one is "member" and another one is "participants". I would like to display the data in table "member" to my local host page and I did it. However, I cannot insert multiple rows of "member" data by using checkbox to my database table "participants". I am stuck. Any help is much appreciated.
<?php
try {
$con = new PDO("mysql:host=localhost;dbname=kgruum member", "root", "");
$sql = $con->query("SELECT * FROM member");
echo "<table class='info' align='center' border='1'>";
echo "<tr><td width='10'></td>
<td width='10'><b>ID</b></td>
<td width='500'><b>Name</b></td>
<td width='50'><b>Handicap</b></td><tr>";
foreach($sql as $row) {
$ID = $row["ID"];
$Name = $row["Name"];
$Handicap = $row["Handicap"];
echo "<tr>
<td><form method='POST' action='Add participant.php'><input type='checkbox' name='insert[]' value='$ID'></td>
<td>$ID</td>
<td>$Name</td>
<td>$Handicap</td><tr>";
}
echo"</table><div align='center'><input type='image' value='submit' src='add selected button.png' alt='submit Button' onmouseover='this.src='pink add selected button.png'' onmouseout='this.src='add selected button.png'' name='add_btn' id='add_btn'></div><br></form>";
if(isset($_POST['add_btn'])) {
if(!empty($_POST['insert'])) {
foreach($_POST['insert'] as $check) {
$st=$con->prepare("INSERT INTO participants(ID,Name,Handicap) VALUES('$ID','$Name','$Handicap')");
$insert->bindParam('ID',$ID);
$insert->bindParam('Name',$Name);
$insert->bindParam('Handicap',$Handicap);
$st->execute();
}
echo "<script type='text/javascript'>
alert('Successful Insert ! ');
window.location.href = 'Add participant.php';
</script>";
} else {
echo "<script type='text/javascript'>alert('You didn't choose which user you want to insert ! ')</script>";
}
}
} catch(PDOException $e) {
echo "error".$e->getMessage();
}
?>
You are not storing the $Name and $Handicap values in the insert[] array, you only storing the $ID value.
To resolve, do something like this:
<input type='checkbox' name='insert[]' value='$ID|$Name|$Handicap'>
Then:
foreach($_POST['insert'] as $check) {
$values = explode('|', $check);
$ID = $values[0];
$Name = $values[1];
$Handicap = $values[2];
//The rest of your SQL code goes here as you have it...
$check = '';
}

How can I reset index to 0

i should make a "cheque" and there should be (Index,id,....), but index should reset after 100, but id must be auto_incremented.
Here is my code what i did. I didnt get how can i reset index to 0. I cant even show the indexs value, it shows 0 everytime when i add something.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "dbcar";
$number = "";
$state_number = "";
$model = "";
$status = "";
$conditions = "";
$date = "";
$number_index = "1";
$connect = mysqli_connect($host,$user,$password,$database);
echo "<h1>Report Log </h1>";
$sqlget = "SELECT * FROM carserv ORDER BY date DESC LIMIT 1";
$sqldata = mysqli_query($connect,$sqlget) or die("error");
echo "<table>";
echo"<tr>
<th>INDEX</th>
<th>ID</th>
<th>State Number</th>
<th>Model</th>
<th>Status</th>
<th>Condition</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($sqldata,MYSQLI_ASSOC)){
echo" <tr><td>";
echo $row['number_index'];
echo" </td><td>";
echo $row['number'];
echo" </td><td>";
echo $row['state_number'];
echo" </td><td>";
echo $row['model'];
echo" </td><td>";
echo $row['status'];
echo" </td><td>";
echo $row['conditions'];
echo" </td><td>";
echo $row['date'];
echo" </td></tr>";
}
echo "</table>";
function getPosts(){
$posts = array();
$posts[0] = $_POST['state_number'];
$posts[1] = $_POST['number'];
$posts[2] = $_POST['model'];
$posts[3] = $_POST['status'];
$posts[4] = $_POST['conditions'];
$posts[6] = $_POST['number_index'];
return $posts;
}
?>
and here is my output: http://imgur.com/GOuCcBU
Take look in your phpmyadmin page there is auto_increment option you need to just have two field check auto increment for id field and for index you just fetch it and save it to db in another field with name number_index(because index is a reserved word).
Reset your db to O by doing something like this is your counter_update.php
if($_POST['index_reset']) {
$index_reset = $_POST[index_reset];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = 'UPDATE counters SET number_index =\'0\' WHERE Page = \'$index_reset\';';
}
And html side something like this
$page_reset = "<form id='Reset' action='counter_update.php' method='post'>
<button type='submit' name='index_reset' value='$formPage'>RESET</button>
</form>";

mysql two different queries into two different html tables

I want to run two different mysql queries and output results into two different html tables. I'm opening one DB connection and fetching two entirely different result sets.
I have one page that I want to show two different 's in the page, each table is the results from different query.
echo "<table class='table table-striped table-bordered table-hover table-condensed'>";
echo "<thead><tr>";
echo "<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th>";
echo "</tr></thead></table>";
while ($rowA = mysql_fetch_array($result)) {
echo "<tbody><tr>";
echo "<td>".$rowA['LAST']."</td>";
echo "<td>".$rowA['FIRST']."</td>";
echo "<td>".$rowA['MDC']."</td>";
echo "<td>".$rowA['RADIO']."</td>";
echo "<td>".$rowA['ePCR']."</td>";
echo "<td>".$rowA['Firehouse']."</td>";
}
echo "</tr></tbody></table>";
echo "<table class='table table-striped table-bordered table-condensed'>";
echo "<thead><tr>";
echo "<th>USERNAME</th><th>CLASSNAME</th><th>DATE COMPLETED</th>";
echo "</tr></thead></table>";
while ($rowB = mysql_fetch_array($sql)) {
echo "<tbody><tr>";
echo "<td>".$rowB['UserName']."</td>";
echo "<td>".$rowB['ClassName']."</td>";
echo "<td>".$rowB['DateCompleted']."</td>";
}
echo "</tr></tbody></table>";
mysql_close($dbhandle);
here is my query:
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("tech_training",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT LastName AS LAST, FirstName AS FIRST,
MAX(IF(`ClassName`='MDC (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'MDC',
MAX(IF(`ClassName`='800 MHz Radio (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'RADIO',
MAX(IF(`ClassName`='ePCR (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'ePCR',
MAX(IF(`ClassName`='Firehouse (Incident)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'Firehouse'
FROM EnrollmentsTbl INNER JOIN UsersDataTbl ON EnrollmentsTbl.UserName = UsersDataTbl.UserName
GROUP BY EnrollmentsTbl.UserName
ORDER BY LastName
LIMIT 20;");
//execute the second SQL query and return records
$sql = mysql_query("SELECT UserName, ClassName, DateCompleted FROM EnrollmentsTbl LIMIT 10;");
Somewhere at the top of the page, or preferably use an include statement since according to PSR 1 you should not have output mixed with functions/classes.
Use PDO and here is an example.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query('SELECT * FROM table');
$rowA = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $db->query('SELECT * FROM table2');
$rowB = $stmt->fetchAll(PDO::FETCH_ASSOC);
ANSWER
echo "<tbody>"; //this is outside
while ($rowB = mysql_fetch_array($sql)) {
echo "<tr>";
echo "<td>".$rowB['UserName']."</td>";
echo "<td>".$rowB['ClassName']."</td>";
echo "<td>".$rowB['DateCompleted']."</td>";
echo "</tr>";// MOVE THIS INSIDE THE LOOP!!!
}
echo "</tbody></table>";
other loop:
echo "<tbody>"; //outide
while ($rowA = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$rowA['LAST']."</td>";
echo "<td>".$rowA['FIRST']."</td>";
echo "<td>".$rowA['MDC']."</td>";
echo "<td>".$rowA['RADIO']."</td>";
echo "<td>".$rowA['ePCR']."</td>";
echo "<td>".$rowA['Firehouse']."</td>";
echo "</tr>"; //move end row here
}
echo "</tbody></table>";
EXPLANATION
//you have some array
$result = [];
echo "<table>" // you only want one of these
foreach($results as $rows){
echo "<tr>";
echo "<td>data</td><td> mode data </td>";
echo "</tr>"; close row each time
}
echo "</table>" //close it ONLY ONCE!
Recommendation
Proper and readable formatting would of saved you. EX:
echo "<table class='table table-striped table-bordered table-hover table-condensed'>
<thead>
<tr>
<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th></tr>
</thead>
</table>";
OR:
$table = <<<HTML
<table class='table table-striped table-bordered table-hover table-condensed'>
<thead>
<tr>
<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th></tr>
</thead>
</table>
HTML;
echo $table;

Similar Queries different results, why?

This one is a bit perplexing since it works perfectly on some records, and not on others. I am trying to pull all records with a specific email and only getting one record in about half of the cases. I have two query sets one pulling the data one is pulling it half of the time.
The first that works all the time is:
$tiera = mysql_query("SELECT SUM(datamb) AS tiera FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tiera1 = mysql_fetch_assoc($tiera);
$tiera2 = $tiera1['tiera'];
$tieradata = mysql_query("SELECT SUM(dataplan) as datatotal FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tieradata1 = mysql_fetch_assoc($tieradata);
$tieradata2 = $tieradata1['datatotal'];
echo "<table id='display1'>
<tr>
<th>Tier:</th>
<th>Total Data in Tier:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
</tr>";
echo "<tr>";
echo "<td>A</td> ";
echo "<td>". $tieradata2 . " MB</td> ";
echo "<td>". $tiera2. " MB</td> ";
echo "<td>".($tieradata1['datatotal'] - ROUND ($tiera1['tiera'],2)) . "MB</td></font> ";
echo "</table>";
I cant use this for my second query because I need it in the loop like this:
$sql = "SELECT phonenumber,date,email, dataplan AS currentplan, SUM(datamb) AS value_sum FROM maindata2 WHERE email='".mysql_real_escape_string($_POST['email'])."' GROUP BY dataplan, phonenumber ";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No Data Found For This Email";
exit;
}
$row = mysql_fetch_assoc($result);
$query = mysql_query($sql) or die(mysql_error());
$header_printed = false;
while($row = mysql_fetch_array($query)) {
if ($row['phonenumber']) {
if ($header_printed === false) {
echo "
<table id='display'>
<tr>
<th>Phone Number:</th>
<th>Data Plan:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
<th>Date Reporting:</th>
</tr>";
$header_printed = true;
}
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "MB</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td><font color=$color>".($row['currentplan'] - ROUND ($row["value_sum"],2)) . "MB</td></font> ";
echo "<td>".$row['date'] . "</td></tr>";
}
}
echo "</table>";
So the question is, what is missing from the second query that is in the first?

Categories