Back with another quick question. I have this code below which echo's out product names from a database. What I want to do is make the echoed out product names a link to another page called product.php, each link needs to have a unique ID, for example
Product Name
How would I go about doing this? Many thanks. I will point out that I am very new to PHP.
<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT product_name FROM Products");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>
Assuming your Products table has a unique ID field called "id", change your select to:
$rs = $conn->execute("SELECT id, product_name FROM Products");
And when you want to create a link, use that field and pass it into the URL. So you'd have product.php?id=<?= $thatIdField; ?>.
Example code:
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
Related
I am using a class that fetches information from a database and shows that information in a table, along with an edit and delete button. When I click the edit or delete button, I want to add $_GET['id'] to the link, but I am confused on how to accomplish this.
public function select($tName,$from,$where=1){
$key=[];
$con=$this->con;
$sql="SELECT $tName FROM $from WHERE $where";
$data = $con->query($sql);
$fullRec=[];
foreach($data as $k=>$rows){
$fullRec[]=$rows;
}
foreach($rows as $k=>$v){
$key[] = $k;
}
//create table
echo "<table border='1'>";
//create one row with col name selected!!
echo "<tr>";
for($z=0;$z<count($key);$z+=2){
echo "<td>".$key[$z]."</td>";
}
echo "<td>actions</td>";
echo "</tr>";
//create one row for each record comes!!
for($i=0;$i<count($fullRec);$i++){
echo "<tr>";
//create one table data for each record comes!!
for($j=0;$j<count($fullRec[$i])/2;$j++){
echo "<td>".$fullRec[$i][$j]."</td>";
}
echo "<td>EditDelete</td>";
echo "</tr>";
}
echo "</table>";
}
use like this to pass the id of the record in get parameter
echo "<a href='your_route?del=".$rows['id']."'>DELETE</a>";
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 would to like to create a dynamic table that the rows and columns of the table depends on the data in mysql data. Please see below my codes.
<?php
require "connect/db.php";
$query = mysqli_query($mysqli, "SELECT COUNT(level) level, shelf_no, bin_id FROM location_bin WHERE rack_id =1 GROUP BY shelf_no");
while($res=mysqli_fetch_array($query)){
$col = $res['level']; //col
$row = $res['shelf_no']; //rows
echo "<table border='1'>";
$i = 0;
while ($i < $col){
if ($i==$col){
echo "<tr>";
}
echo "<td>".$res['bin_id']."</td>";
$i++;
}
echo "</tr>";
echo "</table>";
}
?>
What I want is to display A-1-01 up to A-1-06 in the first row then A-2-01 to A-2-03 on the second row. Note that the data is dynamic.
Can you try this code . It works. change db.php path as your system path.
require "db.php";
$query = mysqli_query($conn, 'SELECT level, shelf_no, bin_id FROM location_bin ORDER BY shelf_no asc, level asc ');
echo "<table border='1'>";
echo "<tr>";
$i=0;
while($res = mysqli_fetch_assoc($query)) {
$row=$res['shelf_no'];
if ($i < $row){
$i=$row;
echo "</tr><tr>";
}
echo "<td>".$res['bin_id']."</td>";
}
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'm having trouble displaying my mysql table using php code. All it displays is the column names not the values associated with them. I know my username password and db are all correct but like I said the table is not displaying the values I added. Any help would be much appreciated This is my mysql code:
CREATE TABLE Guitars
(
Brand varchar(20) NOT NULL,
Model varchar(20) NOT NULL,
PRIMARY KEY(Brand)
);
insert into Guitars values('Ibanez','RG');
insert into Guitars values('Ibanez','S');
insert into Guitars values('Gibson','Les Paul');
insert into Guitars values('Gibson','Explorer');
And this is my php code:
<?php
$db_host = '*****';
$db_user = '*****';
$db_pwd = '*****';
$database = '*****';
$table = 'Guitars';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\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)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
Try this:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "</tr>\n";
}
Update:
Note: You can't make brand as primary key since you gonna add same brand name for different models.
I don't see why you are using the fetch_field call. I'm assuming that you know ahead of time what the actual names of each field in your table is prior to calling it's data? I think for simplicity sake (less loops and nested loops) you should write the name of the fields manually, then loop through the data entering the values.
$feedback .= "<table border='1'><tr>";
$feedback .= "<th>Brand</th><th>Model</th></tr>";
while ($row = mysql_fetch_array($result)) {
$feedback .= "<tr><td>" . $row['Brand'] . "</td>";
$feedback .= "<td>" . $row['Model'] . "</td></tr>";
}
$feedback .= "</table>";
echo $feedback;
By the time you're done displaying the header, the query result's internal pointer will have reached the last row, so your mysql_fetch_row() calls fail because there are no more rows to fetch. Call mysql_data_seek(0); before printing the table rows, to move the internal pointer back to the first row.
You can also try for fetching data
while ($fielddata = mysql_fetch_array($result))
{
echo '<tr>';
for ($i = 0; $i<$fields_num; $i++) // $fields_num already exists in your code
{
$field = mysql_fetch_field($result, $i);
echo '<td>' . $fielddata[$field->name] . '</td>';
}
echo '</tr>';
}