I am trying to pass a variable from a page to another page so that i can display more information on the other page by getting the idea. I am not really sure what is going wrong and because I use bluemix it doesn`t display an error it just gives me the page 500 error. Here is my code:
<?php
$strsql = "select id, name, problem, urgency, technology from idea WHERE status='saved'";
if ($result = $mysqli->query($strsql)) {
// printf("<br>Select returned %d rows.\n", $result->num_rows);
} else {
//Could be many reasons, but most likely the table isn't created yet. init.php will create the table.
echo "<b>Can't query the database, did you <a href = init.php>Create the table</a> yet?</b>";
}
?>
<?php
echo "<tr>\n";
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . "</th>\n"; //the headings
}
echo "</tr>\n";
while ( $row = mysqli_fetch_row ( $result ) ) {
$idea_id= $row['id'];
echo "<tr>\n";
for($i = 0; $i < mysqli_num_fields ( $result ); $i ++) {
echo '<td>' . "$row[$i]" . '</td>';
}
echo "</tr>\n";
}
$result->close();
mysqli_close();
?>
There's a small bug in your code. Your echo <a href ="... line should be like this,
echo '<td>' . $row[$i] . '</td>';
Related
I have a MySQL table field which consists of a URL pointing towards an image. I'm using php and want the image to display in a table along with the other fields.
I think I need to use the PHP Switch statement and reference either the Row('Name') or Field Ref Number to create the code. I have this working fine in classic-asp, but need to code this in php.
$result = mysql_query("SELECT sometext,urlvalue,somemoretext FROM Table");
if (!$result) {
die("Query to show fields from table failed");
// Table fields
// sometext
// urlvalue an http image address such as http://www.example.com/image.jpg"
// somemoretext
$fields_num = mysql_num_fields($result);
echo "<table border='1'>
<tr bgcolor='yellow' align='left'>";
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";
}
echo "\n";
// printing table rows
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
switch $fields_num {
case "2":
// result cell looks like this ---->
// <td><a target='_blank' href='http://www.example.com/image.jpg'><img src='http://http://www.example.com/image.jpg'></a></td>
echo "<td><a target='_blank' href='" . $cell ."'><img src='" . $cell ."'></a></td>";
break;
default:
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
If you know the columns that you are going to be accessing and you know which column is the url, then you can use the following mysqli_-based code block with a condition in the inner loop to check for the matching column name.
If you don't know the columns that you will be dealing with, you can use filter_var($val, FILTER_VALIDATE_URL) assuming you only have one url string in your resultset. If you go for this second option, the one side effect on my code block is that you would have re-engineer the <th> portion.
I refuse to write answers using mysql_ functions, so please take this chance to modernize your code. I've included the connection declaration and basic error checking for your debugging convenience. (Never display error messages on your public site.)
Untested Code:
$columns = ['sometext', 'urlvalue', 'somemoretext'];
if (!$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db")) {
echo "Database Connect Error: " , $mysqli->connect_error;
} elseif (!$result = $mysqli->query("SELECT `" . implode('`, `', $columns) . "` FROM `Table`")) {
echo "Query Syntax Error: " , $mysqli->error;
if (!$result->num_rows) {
echo "No Rows Found";
} else {
echo "<table border='1'>";
echo "<tr bgcolor='yellow' align='left'>";
echo "<th>" , implode("</th><th>", $columns) , "</th>";
echo "</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $col => $val) {
echo "<td>";
if ($col == 'urlvalue') { // or if (filter_var($val, FILTER_VALIDATE_URL)) {
echo "<a target='_blank' href='$val'><img src='$val'></a>";
} else {
echo "$val";
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
I am not completely sure what you mean but rather than referencing the field number just reference the name.
if ($result->num_rows > 0) {
echo "<table border='1'><tr bgcolor='yellow' align='left'>";
while($row = $result->fetch_assoc()) {
echo "<th>".$row['field-name']."</th>";
echo "<tr>";
echo "<td><a target='_blank' href='" . $row['field-name'] ."'><img src='" . $row['field-name'] ."'>
</a>
</td>";
echo "</tr>";
}
echo "</table>";
}
I am trying to get the column names and data from a table using mysqli and php. Any help is appreciated.
I know how to do this in java by more or less this code:
String [] header= new String[numberOfColumns-1];
//Code to get column names in header array
String table = "<table><tr>"
for(int i=0;i<numberOfColumns-1;i++){
table= table + "<td>" + header[i] + </td>;
}
table = table + </tr>;
while(result.next()!=null){
table = table + <tr>
for (int j = 0 ; j < numberOfColumns-1 ; j++){
table = table + <td> + result.getString[j] + </td>
}
table = table + </tr>
}
But i have no idea how to do it in php. Each table is different but what i have to far for the one table:
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>Last Name</td>";
echo "<td>Date of Birth</td>";
echo "<td>Contact Details</td>";
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $rowitem['fname'] . "</td>";
echo "<td>" . $rowitem['lname'] . "</td>";
echo "<td>" . $rowitem['dob'] . "</td>";
echo "<td>" . $rowitem['contact'] . "</td>";*/
echo "</tr>";
}
echo "</table>"; //end table tag
EDIT: Is the implementation of the fetch_fields correct?
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>"
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
for($x =0; $x < count($finfo);$x++){
echo "<td>" . $rowitem[$x] . "/td";
}
echo "</tr>";
}
echo "</table>";
EDIT 2: Database Connection.php
<<?php
include("config.php");
session_start();
$sql = ($_GET['q']);
$result = mysqli_query($db,$sql);
echo "<table border='1' class='table_info'>";
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>";
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
foreach ($row as $value) { (line 18)
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>"; //end table tag
?>
Error:
Notice: Undefined variable: row in databaseConnection.php on line 18
Warning: Invalid argument supplied for foreach() in databaseConnection.php on line 18
You can call mysqli_fetch_fields on the $result object, and retrieve the name property for each object in the returned array. See documentation for examples.
There are a couple ways to do this:
Use array_keys() to grab the names of the keys from an associative array:
$rowitem = mysqli_fetch_array($result, MYSQLI_ASSOC);
$header = array_keys($rowitem);
Use mysqli_fetch_fields() to grab the field objects, and parse out the names into an array using array_map():
// Helper function to use in array_map
// (For PHP < 5.3. If >= 5.3.0, use the second version)
function getFieldName($field) { return $field->name; }
// For PHP < 5.3:
$header = array_map("getFieldName", mysqli_fetch_fields($result));
// For PHP >= 5.3.0:
$header = array_map(function($o) { return $o->name; }, mysqli_fetch_fields($result));
As mentioned you can use $result->fetch_fields() to get the field information from the result and this includes the name of each field.
For what you're trying to acheive this code should work for pretty much any table/query:
<?php
/* Connect to mysql */
$mysqli = new mysqli("localhost", "username", "password", "database");
/* Check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Your query */
$query = "SELECT * from table";
if ($result = $mysqli->query($query)) {
/* Output HTML table */
echo "<table border='1'>";
/* Get field information for all returned columns */
$finfo = $result->fetch_fields();
/* Output each column name in first table row */
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>".$val->name."</td>";
}
echo "</tr>";
/* Fetch the result and output each row into a table row */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$result->free();
echo "</table>";
}
$mysqli->close();
(Obviously you should never query a database from a $_POST variable without some serious sanitisation of the input, but I'll assume that was just for your convenience.)
You can Echo in a table..
$result = mysqli_query($db,$sql)
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);`
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
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>
I have the following bit of code, that selects a table, loops through all the values which match an actor and displays the reviews for that actor.
include("app/config/db.php");
$aid=$actor['id'];
$query = "SELECT * FROM `reviews` WHERE `actor_id` = $aid";
$result = $mysqli->query($query);
$num_results = $result->num_rows;
if( $num_results ){
//loop to show each records
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<span class=\"review-score\">";
echo $row['score']*10;
echo "</span>";
echo " by <strong>";
echo $row['author'];
echo "</strong>";
echo " on <strong>";
echo $row['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $row['body'];
echo "</p>";
echo "</br>";
}
}else{
echo "No records found.";
}
$result->free();
$mysqli->close();
I want to convert to using PDO prepared statements.
This is what I've tried. It doesn't display any of the reviews assigned to the actor. Please help
include("app/config/db.php");
$aid=$actor['id'];
$st = DBase::singleton()
->prepare(
'select * ' .
'from `reviews` ' .
'where `actor_id` like :aid ' .
'limit 0,10');
$st->bindParam(':aid', $aid, PDO::PARAM_STR);
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
echo "<span class=\"review-score\">";
echo $st['score']*10;
echo "</span>";
echo " by <strong>";
echo $st['author'];
echo "</strong>";
echo " on <strong>";
echo $st['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $st['body'];
echo "</p>";
echo "</br>";
}
}
DBase:singleton
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
You're storing each row's result in $row, but not accessing $row when you want to display the data.
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
...
echo $st['score']*10;
The echo line should be:
echo $row->score*10;
You're also fetching objects but accessing the data as an array.
thats how I was taught to write a while loop.. how else could I do it?
My point is that if assign a variable with successive values of the row, then the data is in that variable, not in the object that iterates over rows. What you've done is analogous to this:
for ($i = 0; $i < $count; $i++) {
echo $count;
}
Whereas in that example one should do this instead to get successive values in the loop:
for ($i = 0; $i < $count; $i++) {
echo $i;
}