Why php can't print data from mysql database? - php

PHP failed to print data of two columns of a mysql tableļ¼Œthe result only shows the first row of data which proved to be right,with the rest rows show
" Undefined offset".
$query1='select MNO from mima01 order by MNO;';
$query2='select MTYPE from mima01 order by MNO;';
$result1=mysqli_query($conn,$query1);
$result2=mysqli_query($conn,$query2);
$username=mysqli_fetch_array($result1);
$usertype=mysqli_fetch_array($result2);
$count='select count(*) from mima01;';
$usercount=mysqli_query($conn,$count);
$usernum=mysqli_fetch_array($usercount);
for($i=0;$i<$usernum[0];$i++) {
echo '<tr><td style="text-align:center">' ;
echo $username[$i];
echo '</td>';
echo '<td style="text-align:center">' ;
echo $usertype[$i];
echo '</td></tr>';
}

I've rewritten your code to the normal way you would walk through a query result:
$query = 'select MNO, MTYPE from mima01 order by MNO;';
$result = mysqli_query($conn, $query);
while ($data = mysqli_fetch_array($result)) {
echo '<tr><td style="text-align:center">' .
$data['MNO'] .
'</td>' .
'<td style="text-align:center">' .
$data['MTYPE'] .
'</td></tr>';
}
Please note that I have no way to run this code so I can't be a 100% sure it will work.

from what I understand I think your solution is:
$query='SELECT MNO,MTYPE FROM mima01 ORDER BY MNO DECS;'; //use DECS|ASC
$result=mysqli_query($conn,$query);
$username=mysqli_fetch_array($result);
// to count the rows
$count=mysqli_num_rows($result);;
echo $count;
// to display data
while($row=mysqli_fetch_array($result) {
echo '<tr><td style="text-align:center">';
echo $row['MNO'];
echo '</td>';
echo '<td style="text-align:center">';
echo $row['MTYPE'];
echo '</td></tr>';
}
Hope it was helpful

Related

Limiting column for fetched data in php

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.
Currently I am using the logic below, however I am getting everything in a column.
The goal is to limit the data to a page size so the data can be printed.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?></div>
If I understand your problem correctly you will want to do something like:
Keep a counter to see which number record you're looking at ($i)
$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
// ...
On every 4th iteration of the loop output something like </tr><tr>.
if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
{
echo "</tr><tr>"; // Output your HTML to start a new row
}
One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
</div>

How to fetch all rows of sql query from MySQL database into array in php

I am writing an application to build a chart using the google chart API.
The data is dynamic, and resides in a MySQL database.
The issue being faced is that the array that contains the datasource to be displayed only contains the first row returned by the query. Even after looping.
This is the code:
include 'connect.php';
$sql="SELECT result,COUNT(result) value
FROM test
WHERE result LIKE 'GY%'
GROUP BY result";
$result=mysqli_query($link,$sql);
$myurl[]="['Option','Value']";
while($row=mysqli_fetch_assoc($result))
{
$result=$row['result'];
$value=$row['value'];
$Title="My Results";
$myurl[]="['".$result."',".$value."]";
}
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
<?php
echo (implode(",",$myurl));?>
]);
var options={
title:'<?php echo($Title);?> '
};
Only the first row being returned is used in the chart,therefore it shows that value as 100%. How can i ensure ALL the row values are used?
Modify the query like this
$sql="SELECT result value
FROM test
WHERE result LIKE 'GY%'
GROUP BY result";
$result=mysqli_query($link,$sql);
And the number of results you can access like below.
mysqli_num_rows($result)
If you want an associative array, use this:
$query = "SELECT column FROM `table` WHERE id='" . $id . "'"; / Whatever your query is
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
You can then call $row and the column name from the row with a numbered id that is $id by using $row['columnname']; I'm also pretty sure that you can use print_r($row['columnname']); without including the WHERE id='" . $id . "'"; in the query and instead just having $query = "SELECT column FROMtable; and it will print out all of the data (every row) in that column.
Also, if you're just looking to draw data to a chart, using a google API could over complicate things, as you could just output the data to an HTML table with this code:
<?php
$query = "SELECT FROM `table`";
$result = mysql_query($query);
echo '<table class="table">';
echo '<tr class="table">';
echo '<th class="table">Column</th>';
echo '</tr>';
while($row = mysql_fetch_assoc($result)
{
echo '<tr class="table">';
echo '<th class="table">' . $row['column'] . '</th>';
echo '</tr>';
}
echo '</table>';
?>
Add any other things you need using echo in php then the html code. You can also put buttons in the table, and pretty much anything else. This site should give any more info you would need on HTML tables: http://www.w3schools.com/html/html_tables.asp
Here's another little example I made of an HTML form echoed in php. It has buttons, etc.
$query = "SELECT * FROM `users` WHERE status='accepted'";
$result = mysql_query($query) or die(mysql_error());
echo '<table class="table">';
echo '<h2>Accounts</h2>';
echo '<tr class="table">';
echo '<th class="table">Name</th>';
echo '<th class="table">Email</th>';
echo '<th class="table">Username</th>';
echo '<th class="table">Date Created</th>';
echo '<th class="table">Decline</th>';
echo '<th class="table">Accept</th>';
echo '<th class="table">Give Admin</th>';
echo '</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr class="table">';
echo '<th class="table">' . $row['name'] . '</th>';
echo '<th class="table">' . $row['email'] . '</th>';
echo '<th class="table">' . $row['username'] . '</th>';
echo '<th class="table">' . $row['trn_date'] . '</th>';
echo '<form method="post">';
echo '<th class="table"><input type="submit" name="decline_' .$row["id"]. '" value="decline" ></input></th>';
echo '<th class="table"><input type="submit" name="accept_' .$row["id"]. '" value="accept" ></input></th>';
echo '<th class="table"><input type="submit" name="giveadmin_' .$row["id"]. '" value="accept/give admin" ></input></th>';
echo '</form>';
echo '</tr>';
}
echo '</table>';
Hope that helped:)

Element ID changing with each MYSQL Database insert

Ok so I have a script that pulls information from a database and puts it into a table. (the full script is at the bottom of this question)
Each TR is echoed with a standard ID: echo "<tr class='task' id='task1'>"; the only problem with this is each new tr or each row that is pulled from the database gets assigned the same ID task1 This is not good coding technique as well as not working with my javascript for changing the tables class name's based on the information from the database.
So my question is, is there a way to sort of "auto generate" the id name for each tr of the table? I would like to see task1, task2, task3 and so on.
Full code starts here
<?php
$con=mysqli_connect("");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM affiliate_tasks WHERE username = '$_SESSION[username]'";
if( isset($_POST['sort-selection']) && $_POST['sort-selection'] != 'all' )
{
$query .= " AND status = '". $_POST['sort-selection']."';" ;
}
$result = mysqli_query($con, $query);
echo "<table class='table table-message'>
<tr class='heading'>
<td class='cell-title'>Tasks</td>
<td class='cell-status hidden-phone hidden-tablet'>Status</td>
<td class='cell-time align-right'>Due Date</td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr class='task' id='task1'>";
echo "<td class='cell-ttle'>" . $row['task_name'] . "</td>";
echo "<td class='cell-status hidden-phone hidden-tablet'>" . $row['status'] . "</td>";
echo "<td class='cell-time align=right'>" . $row['due_date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If your table row has an unique id column, that will be the best fit here. You can use:
echo "<tr class='task' id='task-" . $row['id'] . "'>";
If not, and you just want a sequential number, you just use a variable like this:
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr class='task' id='task-" . ++$i . "'>";
// Rest of your lines ...
}

SQL Query only retrieving one row

I have a a php website with some code on it to pull from a database after the user has defined some search terms and then show them a table with all their information in it
The problem is even when i do a select * from the tables, i am only getting the first row back.
Code:
$result = mysql_query("SELECT trees.*
FROM trees
INNER JOIN price
ON trees.ID=price.treeid
");
$num_rows = mysql_num_rows($result);
if($num_rows == 0) {
echo "No rows retrieved";
} else {
echo $num_rows;
}
i have 2 rows in my database:
Spruce El Sorbeous Sprucious Green Green Green 100 200
its a tree ma! true NULL NULL NULL
Mayday el daymay red green white 10 4000000
GOING DOWN true Grey true false
when i print out the $num_rows up there, it is only one.
When i print out my table below, there is only one row:
echo '<table border = 0 cellpadding=0 >';
echo '<tr>';
echo '<td><b><u>Name</b></u></td>
<td><b><u>Latin Name</b></u></td>
<td><b><u>Primary Color</b></u></td>
<td><b><u>Secondary Color</b></u></td>
<td><b><u>Fall Color</b></u></td>
<td><b><u>Trunk Color</b></u></td>';
echo '<td><b><u>Description</b></u></td>
<td><b><u>Height</b></u></td>
<td><b><u>Spread</b></u></td>
<td><b><u>Drought Resistant?</b></u></td>
<td><b><u>Flowering?</b></u></td>
<td><b><u>Fruit Producing?</b></u></td>';
echo '</tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>';
echo $row['name'];
echo '</td>';
echo '<td>';
echo $row['latinname'];
echo '</td>';
echo '<td>';
echo $row['primarycolor'];
echo '</td>';
echo '<td>';
echo $row['secondarycolor'];
echo '</td>';
echo '<td>';
echo $row['fallcolor'];
echo '</td>';
echo '<td>';
echo $row['trunkcolor'];
echo '</td>';
echo '<td>';
echo $row['description'];
echo '</td>';
echo '<td>';
echo $row['height'];
echo '</td>';
echo '<td>';
echo $row['spread'];
echo '</td>';
echo '<td>';
echo $row['droughtresistant'];
echo '</td>';
echo '<td>';
echo $row['flowering'];
echo '</td>';
echo '<td>';
echo $row['fruitproducing'];
echo '</td>';
echo '</tr>';
}
echo '<table>';
INNER JOIN will only return values that have NOT NULL values in both tables. You are probably joining stuff with a NULL value. Use a LEFT or a RIGHT join instead!
Since there's no example of the data in the PRICE table, I'm guessing that only one row was joined.
The question remains, why are you doing that JOIN? You're not collecting any data from the PRICE table, so what's the point.
BTW, where in the data is the ID?

Creating a contact list from SQL Database

I am looking to query my database based on what the user would like to search by: Ex. (Zip, City, State, Name, Etc Etc). Let's say I search by zip code, and there are 2 results in my SQL for that zip code.
I would like the results to be displayed in the following format on my webpage:
Company Name
Address
City, State Zip
Contact Us Link Link to Another Page
I use the following code for something similar but I display the results in a table with check-boxes.
<?php
while ($row = mysql_fetch_assoc($result))
{
echo '<tr><td>';
echo '<input type="checkbox" name="selected[]" value="'.$row['order_number'].'"/>';
echo '</td>';
foreach ($row as $key => $value)
echo '<td>'.htmlspecialchars($value).'</td>';
echo '</tr>';
}
?>
I really would like to display the results of the search in the format I explained above. I am lost on how to get the results I want. Any help is much appreciated!!
Thanks
Would it be possible to do this as well:
If the Company Name row in my SQL is blank/empty, skip over that row/entry and go to the next.
What you could do, is pull each piece of information individually from the resulting row (change the fields based on what you pull from the table):
while($row = mysql_fetch_assoc($result))
{
echo htmlspecialchars($row['comp_name']) . '<br />';
echo htmlspecialchars($row['Address']) . '<br />';
echo $row['city'] . ', ' . $row['zip'] . '<br />';
echo 'Contact usSome link';//If it's an email
}
or for table output
while($row = mysql_fetch_assoc($result))
{
echo '<table>'
echo '<tr><td colspan="2">' . htmlspecialchars($row['comp_name']) . '</td></tr>';
echo '<tr><td colspan="2">' . htmlspecialchars($row['Address']) . '</td></tr>';
echo '<tr><td colspan="2">' . $row['city'] . ', ' . $row['zip'] . '<br />';
echo '<tr><td>Contact us</td><td>a href="index.php">Some linke</a></td></tr>';
echo '</table>';
}
Since you are wanting to list the information, you could use an <ul> and output each row as <li>.
<style>
ul { list-style: none; }
</style>
<?php
while ($row = mysql_fetch_array($result)){
echo "<ul>";
echo "<li>".$row["companyName"]."</li><li>".$row["address"]."</li><li>".$row["city"].", ".$row["state"]." ".$row["zipcode"]."</li>";
echo "<li>Contact Us</li><ul>";
}
?>
Also, what is the "Link to Another page"?

Categories