HTML for a PHP function - php

I used prepared statements for my data collection. I am trying to display that data with a fetch_array function in an organized fashion. Is it possible to insert an html table into a php function that relies on a prepared statement?
I've read to use a HEREDOC, but I do not know what to do in place of the variables. I've also tried to create another document for a table, but have the same question.
This is the function I am using.
function showProfile($user) {
global $connection;
$query = "SELECT * FROM profiles WHERE user='$user'";
$result = $connection->query($query);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf(
"%s <br> %s\n",
$row["forename"],
$row["surname"]
) . "<br style='clear:left;'><br>";
}
This is the table I want to use
<table width="398" border="0" align="center" cellpadding="0">
<tr>
<td height="26" colspan="2">Your Profile Information </td>
</tr>
<tr>
<td width="82" valign="top"><div align="left">FirstName:</div></td>
<td width="165" valign="top"><?php echo $forename ?></td>
</tr>
<tr>
<td valign="top"><div align="left">LastName:</div></td>
<td valign="top"><?php echo $surname ?></td>
</tr>
</table>
I can display my data with the function, however, I want to display it in a more organized way.

instead of printf(), you can just echo
echo "<table width='398'> <-- check here the quote marks so the string doesnt break
<tr>
<td>".$row['forename']."</td> <- then concat all the variables you want like this
</tr>
</table>";

I have not tested but this function but it should work. I have wrapped the table rows, in a while loop, although it may not be necessary if you are getting back one row in your query.
function showProfile($user)
{
global $connection;
$query = $connection->prepare("SELECT * FROM profiles WHERE user = :user ");
$query->bindValue(':user', $user);
$result = $query->execute();
echo "<table width='398' border='0' align='center' cellpadding='0'>
<tr><td height='26' colspan='2'>Your Profile Information </td>
</tr> ";
/* associative array */
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "
<tr>
<td width='82' valign='top'><div align='left'>FirstName:</div></td>
<td width='165' valign='top'>{$row['forename']}</td>
</tr>
<tr>
<td valign='top'><div align='left'>LastName:</div></td>
<td valign='top'>{$row['surname']}</td>
</tr>";
}
echo "</table>";
}

As much as possible, you want to separate logic from presentation. Your table example is definitely on track. However, I would suggest thinking a little differently about the output of the function. Instead of the function returning HTML, have it return data that a view could use.
An object is much better suited for the task than a single function:
<?php
class Profile {
private $conn;
private $result;
public function __construct($conn) {
$this->conn = $conn;
}
public function findProfile($user) {
$query = “SELECT * FROM profiles WHERE user=?”;
$stmt = $this->conn->prepare($query);
$stmt->bind_param(‘s’, $user);
$stmt->execute();
$this->result = $stmt->get_result();
}
public function fetch() {
//if($row = $this->result->fetch_array(MYSQLI_ASSOC)) {
if($row = $this->result->fetch_assoc()) {
return $row;
}
return false;
}
}
Then your table can be separated into its own file, to be included whenever you wish (assuming $conn and $user are defined):
<?php
$p = new Profile($conn);
$p->findProfile($user);
?>
<!— html stuff here —>
<?php if($info = $p->fetch()): ?>
<table width="398" border="0" align="center" cellpadding="0">
<tr>
<td height="26" colspan="2">Your Profile Information </td>
</tr>
<tr>
<td width="82" valign="top"><div align="left">FirstName:</div></td>
<td width="165" valign="top"><?= $info[‘forename’] ?></td>
</tr>
<tr>
<td valign="top"><div align="left">LastName:</div></td>
<td valign="top"><?= $info[‘surname’] ?></td>
</tr>
</table>
<?php endif; ?>

Related

Cannot call value from mysql

I've tried many times to call the values but it's failed. Maybe my code is not perfect enough.
loginprocess.php //this is the process to call the value
<?php
include("connection.php");
$noic = mysql_real_escape_string($_POST['noic']);
$katalaluan = md5(mysql_real_escape_string($_POST['katalaluan']));
$query = mysql_query("SELECT * FROM daftar_pengguna WHERE noic = '".$noic."'
AND katalaluan = '".md5."'");
$count=mysql_num_rows($query);
if($count==0)
{
echo "Tiada rekod di jumpai.<br>";
echo "<a href='index.php'>Kembali</a>";
}
else
{
$row=mysql_fetch_array($query);
echo("<script>location.href = 'carianstatuspemohonresult.php?
id=$row[noic]';</script>");
}
?>
userinfo.php //this is to display the value
<?php
include ("connection.php");
$getId=$_REQUEST["id"];
$query= "SELECT * FROM daftar_pengguna WHERE noic='$getId'";
$result=mysql_query($query);
<table width="50%" border="1" align="center">
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><b>NAMA</b></td>
<td align="center"><?php echo $row["nama"];?></td>
</TR>
<TR>
<td align="center"><b>NO IC</b></td>
<td align="center"><?php echo $row["noic"];?></td>
</TR>
<TR>
<td align="center"><b>KATA LALUAN</b></td>
<td align="center"><?php echo $row["katalaluan"];?></td>
</TR>
<TR>
<td align="center"><b>JAWATAN</b></td>
<td align="center"><?php echo $row["jawatan"];?></td>
</tr>
<tr>
<td align="center"><b>PERINGKAT</b></td>
<td align="center"><?php echo $row["peringkat"];?></td>
</tr>
<tr>
<td align="center"><b>EMAIL</b></td>
<td align="center"><?php echo $row["email"];?></td>
</tr>
<?php } ?>
</td></table>
And sorry. I'm using mysql. Hope you can help me fix them even though I'm using the mysql. Also, hope you can understand the code without understanding the malay language.
Tell me if you need to see other code.
I've changed them. It's the same result. No values called. Hmmm.. :(
You create a md5 value from a posted value, but aren't including it in your WHERE clause... Try ...
$query = mysql_query("SELECT * FROM daftar_pengguna WHERE noic = '".$noic."'
AND katalaluan = '".$katalaluan."'");
You have two while fetching data on userinfo.php file:
while($row=mysql_fetch_array($result)){ // <- Remove this one
?>
<table width="50%" border="1" align="center">
<?php
while($row=mysql_fetch_array($result))
Later in the first file use proper quotes around "noic":
echo("<script>location.href = 'carianstatuspemohonresult.php?
id=$row['noic']';</script>"); //<-- noic => 'noic'
It seems that you have to remove the first one.
EDIT: Also, you should follow the #DuaneLortie solution and use the variable you've created in your query:
$query = mysql_query("SELECT * FROM
daftar_pengguna
WHERE noic = '".$noic."'
AND katalaluan = '".$katalaluan."'");
Your code has a sintax error. md5 is a function and you are using as a variable.
You should stop using mysql_* functions since it's deprecated in PHP 5.5 and removed in PHP 7. And finally, md5 hash isn't secure for hashing passwords. Use bcrypt instead.

How to display search results in one table with PHP & MySQL

I have the code to do the search. But the search results are not in the same table. All search results appear in a different table. How do I make them appear in one table?
screenshots :
<?php if(isset($_POST['submit']))
{
if(empty($_POST['word'])){
echo "<center>Title do not match. Please insert the correct title.</center>";}
else {
if(isset($_POST['word'])&& !empty($_POST['word']))
{
require 'config.php';
$word = $_POST['word'];
$query="SELECT * FROM data WHERE word LIKE '%" . $word . "%'";
$sql = $conn->query($query); ?>
<?php if(!$sql)
{
echo "<center>No Record</center>";
}
?>
<table align="center" border="0" >
<tr>
<td width="900">
<?php while($row = $sql->fetch_assoc()){
$dataID = $row['dataID'];
?>
<?php if($sql ==true){?>
<table class="table table-bordered table-hover table-striped">
<tr>
<td width="258" align="center" class="style5">TITLE</td>
<td width="170" align="center" class="style5">MENTION</td>
</tr>
<tr>
<td style="text-transform:uppercase" align="center"> <span style="text-transform:uppercase"><?php echo $row{'word'};?></span> </td>
<td style="text-transform:uppercase" align="center"><span style="text-transform:uppercase"><?php echo $row{'mention'};?></span></td>
</tr>
<?php }}} ?>re
Where do we start?
1.) Try avoiding styling in your html. It isn't forbidden, but your global style is better of when used with CSS.
http://www.w3schools.com/css/
For exampe: Imagine this rule:
<td style="text-transform:uppercase" align="center"> <span style="text-transform:uppercase"><?php echo $row{'word']; ?></span> </td>
that could also be:
<td>
<a href="admindisplay.php?id=<?php echo $row['dataID']; ?>">
<?php echo $row['word'];?>
</a>
</td>
2.) Try indenting. Use an IDE (Notepad with some extra highlighting features and nice indenting. By structuring and neatly placing the brackets "[] {} and ()" you make code more readable and make it easier to DEBUG your own code.
3.) When using SQL, your input should ALWAYS be escaped. Maybe I'm wrong and you have a DB class that does this for you. Although, you should ALWAYS be aware of this: This could prevent SQL Injection and might one day safe your life (or your job).
Escaping: Making your query safe and let it do only thing you want it to do.
SQL INJECTION: Adding malicous characters and code to INPUT so your QUERY does other things than you want.
4.) Try structering what you are doing or the goal you're trying to reach.
<?php
Class DoSearch()
{
protected $search_string;
public function __construct()
{
if(!$this->verify())
return $this->__html('<center>Title do not match. Please insert the correct title.</center>');
$this->search()
}
public function verify()
{
if(isset($_POST['word']))
return false;
if(empty($_POST['word']))
return false;
global $conn;
$this->search_string = $conn->escape($_POST['word']);
return true;
}
public function search()
{
global $conn;
$query = "SELECT * FROM data WHERE word LIKE '%" . $this->search_string . "%'";
$sql = $conn->query($query);
if(!$sql)
return $this->__html('<center>No Record</center>');
$table = array();
$i = 0;
$tableHtml = '
<table class="table table-bordered table-hover table-striped">
<tr>
<th width="258" align="center" class="style5">TITLE</th>
<th width="170" align="center" class="style5">MENTION</th>
</tr>';
while($row = $sql->fetch_assoc())
{
$tableHtml .= '
<tr>
<td style="text-transform:uppercase" align="center"> <span style="text-transform:uppercase">'.$row['word'].'</span> </td>
<td style="text-transform:uppercase" align="center"><span style="text-transform:uppercase">'. $row['mention'].'</span></td>
</tr>
';
}
$tableHtml .= '
</table>
';
return $this->__html($tableHtml);
}
public function __html($msg)
{
echo $msg;
}
}
require_once 'config.php';
$search = new DoSearch();
Move your table code outside of your loop, and only create a new row each time you loop. You were creating a new table each time you loop.
<table class="table table-bordered table-hover table-striped">
<tr>
<td width="258" align="center" class="style5">TITLE</td>
<td width="170" align="center" class="style5">MENTION</td>
</tr>
<?php while($row = $sql->fetch_assoc()){
$dataID = $row['dataID'];
?>
<?php if($sql ==true){?>
<tr>
<td style="text-transform:uppercase" align="center"> <span style="text-transform:uppercase"><?php echo $row{'word'};?></span> </td>
<td style="text-transform:uppercase" align="center"><span style="text-transform:uppercase"><?php echo $row{'mention'};?></span></td>
</tr>
<?php }}} ?>
Don't create a table each time a loop run. Make it simple.
Updated Code
<?php
if(isset($_POST['submit']))
{
if(empty($_POST['word'])) {
echo "<center>Title do not match. Please insert the correct title.</center>";}
else
{
if(isset($_POST['word']) && !empty($_POST['word']))
{
require 'config.php';
$word = $_POST['word'];
$query="SELECT * FROM data WHERE word LIKE '%" . $word . "%'";
$sql = $conn->query($query); ?>
<?php if(!$sql)
{
echo "<center>No Record</center>";
}
?>
<table class="table table-bordered table-hover table-striped">
<tr>
<td width="258" align="center" class="style5">TITLE</td>
<td width="170" align="center" class="style5">MENTION</td>
</tr>
<?php
if($sql ==true)
{
while($row = $sql->fetch_assoc())
{
$dataID = $row['dataID'];
?>
<tr>
<td style="text-transform:uppercase" align="center">
<a href="admindisplay.php?id=<?php echo $row{'dataID'}?>">
<span style="text-transform:uppercase"><?php echo $row{'word'};?></span>
</a>
</td>
<td style="text-transform:uppercase" align="center">
<span style="text-transform:uppercase"><?php echo $row{'mention'};?></span>
</td>
</tr>
<?}}
else
{?>
<tr>
<td colspan=2>Results Not Found.</td>
</tr>
<?}?>
</table>
<?php
}
}
}
?>
If the result is to be issued only in a (unformated) table, simply use this function:
function show_in_table($arr)
{
$count = count($arr);
$output = "";
if($count>0)
{
reset($arr);
$num = count(current($arr));
$output.= '<table cellpadding="0" cellspacing="0">'."\n";
$output.="<tr>\n";
foreach(current($arr) as $key => $value)
{
$output.="<th>";
$output.=$key." ";
$output.="</th>\n";
}
$output.="</tr>\n";
while ($curr_row = current($arr))
{
$output.="<tr>\n";
$col = 1;
while (false !== ($curr_field = current($curr_row)))
{
$output.="<td>";
$output.=$curr_field." ";
$output.="</td>\n";
next($curr_row);
$col++;
}
while($col <= $num)
{
$output.="<td> </td>\n";
$col++;
}
$output.="</tr>\n";
next($arr);
}
$output.="</table>\n";
}
return $output;
}

MySQL query - IF statement to generate two different rows

I have some issues with below script, essentially what I'm trying to achieve is to grab different product and prices and generate a table which works fine. However, some of the products do have an extra charge, in this case the product will use three rows (price, extra charge and total sum). I'm trying to get the IF statement to work as follows: if the extra charge = 0 then it should only make a single row in the table, if more then 0 it should produce the 3 row version.
Someone have any idea what I'm doing wrong? Thanks in advance!
<?php
$page=basename($_SERVER['PHP_SELF']); /* Returns PHP File Name */
$page_name=str_replace(".php","",$page);
mysql_connect(localhost,$dbuser,$dbpass);
#mysql_select_db($database) or die( "Unable to select database");
$query= ("SELECT * FROM table e
JOIN validdate1 r ON e.datevalid1=r.id
JOIN validdate2 d ON e.datevalid2=d.id
WHERE productpage='$page_name'
ORDER BY productname,price2");
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();?>
<table>
<thead>
<tr>
<th class="headerdesc">Description</th>
<th class="headerprice1 rates1">2015</th>
<th class="headerprice2 rates2">2016</th>
</tr>
</thead>
<?php $i=0;while ($i < $num)
{
$productname = mysql_result($result,$i,"productname");
$price1=mysql_result($result,$i,"price1");
$price2=mysql_result($result,$i,"price2");
$extracharge1=mysql_result($result,$i,"extracharge1");
$extracharge2=mysql_result($result,$i,"extracharge2");
$daterange1=mysql_result($result,$i,"daterange1");
$daterange2=mysql_result($result,$i,"daterange2");
if ($extracharge1 > "0") {
echo " <tr>
<td class="desc"><?php echo $productname; ?></td>
<td class="price1 rates1">$<? echo $price1; ?></td>
<td class="price2 rates2">$<? echo $price2; ?></td>
</tr>
<tr>
<td class="extra">Extra Charge**</td>
<td class="price1 rates1">$<? echo $extracharge1; ?></td>
<td class="price2 rates2">$<? echo $extracharge2; ?></td>
</tr>
<tr class="lastrow">
<td class="totalprice"><strong>Total price</strong></td>
<td class="total rates1"><strong>$<? echo $price1+$extracharge1; ?></strong></td>
<td class="total rates2"><strong>$<? echo $price2+$extracharge2; ?></strong></td>
</tr>";
} else {
echo " <tr class="lastrow">
<td class="extra"><?php echo $productname; ?></td>
<td class="price1 rates1">$<? echo $price1; ?></td>
<td class="price2 rates2">$<? echo $price2; ?></td>
</tr>";
}
?>
<?php $i++;}?>
</table>
You have several error in code, change it like this, on the top below query
$num=mysql_numrows($result); will be
$num=mysql_num_rows($result);
don't close the connection since you are still performing queries below
//mysql_close(); comment it out and move it to bottom
and here you need this
if (mysql_num_rows($extracharge1) > 0 )
You are comparing string with a resource in your code
note: Don't use mysql_* functions its deprecated, use PDO or mysqli_*

If IDs from two different tables are equal, display name from another table

I'm writing a code for my little admin panel, and since I'm not that advanced of a coder, I'm experiencing some troubles with getting a name using two different tables.
Here's my code so far:
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
include 'db_connect.php';
$sql = "SELECT * FROM $tbl_name WHERE is_dead='0'";
$result=mysql_query($sql);
?>
<title>Title</title>
<center><img src="header.png"></center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<? include 'menu.php';?>
</tr>
<tr>
<td align="center"><strong>ID</strong></td>
<td align="center"><strong>Unique ID</strong></td>
<td align="center"><strong>Model</strong></td>
<td align="center"><strong>Last Online</strong></td>
<td align="center"><strong>Options</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['id']; ?></td>
<td><? if ($rows['unique_id'] == 7815684) { echo '<font color="blue"><b><u>7815684</u></b></font>'; }
elseif ($rows['unique_id'] == 2312964) { echo '<font color="blue"><b><u>2312964</u></b></font>'; }
else { echo $rows['unique_id']; } ?></td>
<td><? echo $rows['model']; ?></td>
<td align='center'><font color="green"><b><? echo $rows['last_updated']; ?></b></font></td>
<td align="center">update
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
So what I'm trying to do is to get user name, using two tables $tbl_name and $prtalbe using their unique_id. So, if unique_id from $tbl_name equals unique_id from $prtable, I want to show user's name from $prtalbe.
I've been trying another sql query:
$sql = "SELECT * FROM $tbl_name, $prtable WHERE $tbl_name.unique_id = $prtable.unique_id;
$result=mysql_query($sql);
Then doing while loop to get it working
while($rows=mysql_fetch_array($result)){
$rows['name'];
}
and it did work actually, but it didn't want to put it right into my code, since ID from $prtable and $tbl_name are different.
Try this:
$sql = "SELECT $prtable.username FROM $tbl_name INNER JOIN $prtable ON ($tbl_name.unique_id = $prtable.unique_id)";
When you call INNER JOIN you are fetching all rows from each table and combining them given the ON condition. For more information, see this: http://www.w3schools.com/sql/sql_join_inner.asp

mysqli query returns row with no data

In a php code, I am trying to retrieve values of a row in a database. I want my query to be secure so I used mysqli with prepared statement. However, after fetching the row and trying to echo the results, I get null values for whatever I echo. What could be the reason?
Below is the part in my code that fetches and echo the result.
// get value of id that sent from address bar
$id=$_GET['id'];
////$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$sql = $mysqli -> prepare("SELECT topic, detail, name, email, datetime FROM $tbl_name WHERE id=?");
$sql -> bind_param ("s", $id);
$sql -> execute();
/* store result */
// $sql->store_result();
// echo "NUMBER IS : " . "$sql->num_rows";
$sql -> bind_result($topic, $detail, $name, $email, $datetime);
$rows = $sql -> fetch();
////$result=mysql_query($sql);
////$rows=mysql_fetch_array($result);
$sql -> close();
?>
<table width="90%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td width="30%" align="left" bgcolor="#FFFFFF"><IMG name="pictureposition1" border="0" alt="" SRC="images/concordia_logo.jpg" ><br></td>
<td width="30%" colspan="5" align="center" bgcolor="#FFFFFF"><h1><font COLOR=#800517>PHP Forum</font></h1> </td>
<td width="30%" colspan="5" align="right" bgcolor="#FFFFFF"><h3><font COLOR=#800517>CMPE and SOFE 495 Computer Security</font></h3> </td>
</tr>
<tr>
<td><font COLOR="#FFFFFF">.</font></td>
</tr>
</table>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td><table width="100%" border="0" cellpadding="3" cellspacing="1" bordercolor="1" bgcolor="#FFFFFF">
<tr>
<td bgcolor="#F8F7F1"><strong><?php echo $rows['topic']; ?></strong></td>
</tr>
<tr>
<td bgcolor="#F8F7F1"><?php echo $rows['detail']; ?></td>
</tr>
<tr>
<td bgcolor="#F8F7F1"><strong>By :</strong> <?php echo $rows['name']; ?> <strong>Email : </strong><?php echo $rows['email'];?></td>
</tr>
<tr>
<td bgcolor="#F8F7F1"><strong>Date/time : </strong><?php echo $rows['datetime']; ?></td>
</tr>
</table></td>
</tr>
</table>
<BR>
You are binding result so there is no need to assign result of fetch into new variable so try as below
$sql -> bind_result($topic, $detail, $name, $email, $datetime);
$sql -> fetch();
echo $topic."<br>";
echo $detail."<br>";
See PHP Manual for more detail: http://www.php.net/manual/en/mysqli.prepare.php
I think the problem is that the result from the DB query is an object.
Try this,
$rows[0]->name instead of
$rows['name']
If there are multiple rows. get the count of the result using
$count = count($row);
Then go for a for loop
for($i = 0;$i < $count; $i++){
$rows[$i]->name;
}

Categories