So, I have a MySQL database that list users as managers or employees. I want to change the menubar that they see based on the properties. I did have all this done in php, but when going through a re-design I thought about putting it in html files, but I can't quite figure out how this should work.
Here is the php code that I was using to do the operation in the file menubar2.php:
<?php
$email = $_SESSION['logname'];
$results = "SELECT email FROM manager_list WHERE email = '$email'";
$results = mysqli_query($cxn, $results) or die("Query died: query");
$numrows = mysqli_num_rows($results);
if ($numrows == 0)
{
echo"<div id='menu'>";
echo"<ul>";
echo"<li><a href='index2.php'>Quick Review</a></li>";
echo"<li><a href='myPerformance.php'>My Peformance</a></li>";
echo"<li><a href='myGoals.php'>My Goals</a></li>";
echo"<li><a href='sHelp.php'>Help</a></li>";
echo"</ul>";
echo"</div>";
}
if ($numrows > 0)
{
echo"<div id='menu'>";
echo"<ul>";
echo"<li><a href='index2.php'>Quick Review</a></li>";
echo"<li><a href='myPerformance.php'>My Peformance</a></li>";
echo"<li><a href='myGoals.php'>My Goals</a></li>";
echo"<li><a href='toolsManager.php'>Manager Tools</a></li>";
echo"<li><a href='sHelp.php'>Help</a></li>";
echo"</ul>";
echo"</div>";
}
?>
And here is where I was using it (index.html)
<?php
include('sessionauth.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>TinyEval</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrapper">
<?php
include('header2.php');
include('menubar2.php');
?>
<!-- begin #page -->
<div id="page">
<div id="content">
<div class="post">
<h2 class="title">Frequently Asked Questions</h2>
<div class="entry">
<p>How do I fix my headers?</p>
</div>
</div>
</div>
</div>
<div style="clear: both;"> </div>
<!-- end #page -->
</div>
<?php include('footer2.php'); ?>
</body>
</html>
Is there a way I can do this without the include for the menubar2.php - that is, put it all in the html file itself, but without having to use all the echo statements?
Sorry for the newb question, but I'm driving myself batty trying to figure out how html and php/MySQL all tie together.
Thanks!
This approach is solid, so long as you name your index file index.php. PHP was originally an HTML templating language, and using it like this with includes for portions of the page is perfectly correct. You could put that code directly into index.php, but using includes makes your code more reusable. Also, here is simpler and more DRY way to alter the menu when you get more than 0 rows back:
$numrows = mysqli_num_rows($results);
//these lines get echoed in both cases
echo "<div id='menu'>";
echo "<ul>";
echo "<li><a href='index2.php'>Quick Review</a></li>";
echo "<li><a href='myPerformance.php'>My Peformance</a></li>";
echo "<li><a href='myGoals.php'>My Goals</a></li>";
if ($numrows > 0) {
echo "<li><a href='toolsManager.php'>Manager Tools</a></li>";
}
echo "<li><a href='sHelp.php'>Help</a></li>";
echo "</ul>";
echo "</div>";
To expand just a bit further on PHP - it's a server-side language, meaning it does not run in the user's browser like Javascript. When the browser requests a page that ends in PHP, the server runs the script, prints out the results (usually as HTML) and gives the browser only the rendered output. In this case, even though your main index.php and the includes all have php scripts in them, what appears in the browser is the output of the script only.
Related
In this code I'm trying to create as many modal boxes as the rows of my query result. This works! Then I want to fill these modal boxes with as many checkboxes as the number $row['seats_no'] from database. Here we have a problem..in every modal box it creates the same amount of checkboxes as the first one. What I mean is that the $row['seats_no'] has the number from the first row in every row.
<?php
session_start();
if(!isset($_SESSION['name']) && !isset($_SESSION['email']) && !isset($_SESSION['id']) && !isset($_SESSION['cash'])){
header("location: Start.php");
}
$name=trim($_SESSION['name']);
$email=trim($_SESSION['email']);
$dbc = mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($dbc,"SET NAMES 'utf8'");
mysqli_query($dbc,"SET CHARACTER SET 'utf8'");
if (isset($_POST['buy']) && isset($_POST['consert_id'])){
$q = "SELECT ticket_id, section, cost, seats_no FROM tickets INNER JOIN concert ON tickets.consert_id=concert.concert_id WHERE concert.concert_id=".$_POST['consert_id'];
//ticket_id, concert_id, section, cost, seats_no, concert_id,concert_name, date, place, category, description
$r = mysqli_query($dbc,$q);
$num= mysqli_num_rows($r);
$q1 = "SELECT * FROM concert WHERE concert_id=".$_POST['consert_id'];
$r1 = mysqli_query($dbc,$q1);
$first = mysqli_fetch_assoc($r1)
?>
<!DOCTYPE html>
<html>
<title>Seats</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link type="text/css" rel="stylesheet" href="seats_style.css">
<body>
<div style="z-index:1;position:fixed;">
<ul>
<li>E-Viva</li>
<li>Ανανεωση υπολοιπου</li>
</ul>
</div>
<div class="background">
<div class="transbox">
<div class="w3-container">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/199011/concert.png">
<h1><?=$first['concert_name']?></h1>
<div style="left:0;"><?=$first['date']?></div>
<div style="right:0;"><?=$first['place']?></div>
<p><?=$first['description']?></p>
<?php
while ($row = mysqli_fetch_array($r)) {
?>
<div style="margin-left:5em;padding:5px;"><?=$row['section']?></div>
<div style="margin-left:5em;padding:5px;">Τιμή <?=$row['cost']?>€</div>
<div style="margin-left:5em;padding:5px;"><button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Κράτηση</button></div>
<div id="id01" class="w3-modal" background="black">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
<p><h2>Διαλεξε τις θεσεις που θες</h2></p>
<form action="buy.php" method="post">
<table>
<?php
$num=0;
for($j=1; $j<=10; $j++){
echo "<tr>";
for($i=1; $i<= $row['seats_no']/10; $i++){
$num++;
echo "<td><input class='seat' type=\"checkbox\" name=\"s[]\" id=\"".$num."\" value=\"".$num."\"><label for=\"".$num."\">".$num."</label><input type='hidden' name='ticket_id' value='".$row['ticket_id']."'><input type='hidden' name='cost' value='".$row['cost']."'></td>";
}
echo "</tr>";
}
echo "</table><input class=\"ok\" type=\"submit\" name=\"ok\" value=\"Κράτηση\"></form></div></div></div><br>";
}
}
mysqli_free_result($r1);
mysqli_free_result($r);
mysqli_close($dbc);
?>
</div>
</div>
</div>
</body>
</html>
here are the results i get from executing my query at phpMyAdmin
Here are the buttons I create to open the modals
And here is the modal from the last button i clicked that in the database shows it should be 60 checkboxes but it shows 180
Κατερίνα,
Try to change the while ($row = mysqli_fetch_array($r)) {...} with a foreach loop,
like as foreach( mysqli_fetch_array($r) as $row ) {....}
Just a thought.
Also, you close one bracket too soon, remove one before the first mysqli_free_result($r1) and close it after the closing html tag </html> at the end of the file.
Also, as #tadman said, do some research and use parameterized queries. Your code it's very prone to MySQL Injections and you will face several problems. As far as i can see that page has to do with payments, or pre-payment.
Anyways, i hope i helped you.
Καλή επιτυχία ;)
I am still very new to MySQL/PHP and am trying to make code that will loop through my whole SQL table. I was able to do that, to clean things up I wanted to use an html table to store the values in to make things look neater. I tried adding the HTML code into the string which gets printed at the bottom of the code in the HTML section, but the table borders do not show. What am I doing wrong and how can I fix this? Both code and screenshot of output are below:
<?php
include("connection.php");
$query= "SELECT * FROM schedule";
$result = mysqli_query($link, $query);
$scheduletext="<table>";
if($result = mysqli_query($link, $query)) {
while ($row=mysqli_fetch_array($result)) {
$scheduletext="<tr><td>".$scheduletext.$row[1]."</td>";
$scheduletext="<td>".$scheduletext.$row[2]."</td>";
$scheduletext="<td>".$scheduletext.$row[3]."</td>";
$scheduletext="<td>".$scheduletext.$row[4]."</td></tr>";
}
}
$scheduletext=$scheduletext."</table>";
?>
<html>
<head>
<title>TastySnack - Production Schedule</title>
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tasty.css">
</head>
<body>
<div id="top">
<div id="top-left">
TastySnack Production
</div>
<div id="top-right">
<img id="logo" src="images/TastysnackLogo.jpg">
</div>
</div>
<div id="split"></div>
<div id="schedule">
<?php
print_r($scheduletext);
?>
</div>
</body>
</html>
Click Here For Screenshot of Output
As #mister martin said in comment use dot to concatinate your string
$scheduletext ="<table>";
if($result = mysqli_query($link, $query)) {
while ($row=mysqli_fetch_array($result)) {
$scheduletext .="<tr><td>".$scheduletext.$row[1]."</td>";
$scheduletext .="<td>".$scheduletext.$row[2]."</td>";
$scheduletext .="<td>".$scheduletext.$row[3]."</td>";
$scheduletext .="<td>".$scheduletext.$row[4]."</td></tr>";
}
}
$scheduletext .="</table>";
I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);
Easy one! I'm trying to code a cheap forum. Coming from a C background, I started to noticed something strange about PHP. While having a function return a string (HTML) inside of a DIV into place, the browser would not print the </DIV> - even when it's echo'ed by itself.
Does PHP decide when it wants to echo certain DOM elements or have limitations on HTML output?
echo "Start<div id='Forum'>";
echo "Forum";
GetFullList();
echo "</div>";
Where, GetFullList() consists of:
function GetFullList(){
$sql="SELECT * FROM `Forum` WHERE `IsReply` =0";
$result=mysql_query($sql);
if (!$result){
echo mysql_error();
}
if($result){
while($ForumEntry = mysql_fetch_assoc($result)){
$IsReply = $ForumEntry["IsReply"];
$ParentPost = $ForumEntry["ParentTopic"];
$f_User = $ForumEntry["User"];
$f_Replies = $ForumEntry["Replies"];
$f_Views = $ForumEntry["Views"];
$f_Time = $ForumEntry["Time"];
$f_Post = $ForumEntry["Post"];
$f_Topic = $ForumEntry["Topic"];
$f_Index = $ForumEntry["Index"];
echo DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index);
GetChildPostsOf($ParentPost);
}
}
}
And DisplayPost() is built as such:
function DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index){
$PostBlock = "<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'><div id='Grp_Cell' style='float:left;'><div id='Tbl_Cel'>User: ".$f_User."</div><div id='Tbl_Cel'>Replies: ". $f_Replies."</div><div id='Tbl_Cel'>Views: ".$f_Views."</div><div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div></div><div id='Grp_Cell' style='float:right;width:600;'><div id='Tbl_Cel'>Subject: ".$f_Topic."</div><div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div><a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a></div>";
return $PostBlock;
}
(Displays a div scaffolding for DB results: the post.)
When I try to echo "< /div>" after GetFullList(), the result is not printed in HTML, leaving the rest of the page to be encompassed under the malformed div.
There are 10 opening divs and 9 closing divs in $PostBlock. A closing </div> should be added where necessary. An easy way to see what the output looks like is to break it into lines like this:
$PostBlock = "
<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'>
<div id='Grp_Cell' style='float:left;'>
<div id='Tbl_Cel'>User: ".$f_User."</div>
<div id='Tbl_Cel'>Replies: ". $f_Replies."</div>
<div id='Tbl_Cel'>Views: ".$f_Views."</div>
<div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div>
</div>
<div id='Grp_Cell' style='float:right;width:600;'>
<div id='Tbl_Cel'>Subject: ".$f_Topic."</div>
<div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div>
<a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a>
</div> ";
So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.