Hi guys I am relatively new to php and am wondering how there is a cleaner way to retrieve data from my database and show it across different parts of the webpage?
For example see my current code...
<?php
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$_SESSION['email']."'");
while($row = mysqli_fetch_array($result)){
if($_SESSION['email'] == $row['email']) {
// If you find the right user with the same E-Mail address, DO SOME COOL THINGS :)
}
echo '<h2>'. $row['username'] . '</h2>' ;
echo 'Hi, I am a ' . $row['yourage'] . ' year old ' . $row['orientation'] . ' ' . $row['gender'] . ' looking for a ' . $row['lookingfor'] . '.<br /><br />';
echo 'I am currently living in the ' . $row['location'] . ' area.';
echo '<button>Get in touch</button>' . '<br>';
echo '<br /><br />';
echo '<hr />';
echo '<h2>About me:</h2>';
echo $row['aboutme'] . '<br>';
}
mysqli_close($mysqli);
?>
If I copy this again on the page it kills the script but wondering what the best practice is?
First of all, a much better approach to this would be to separate your database and view code, for example by using an MVC framework (such as CakePHP).
But here is what I would do if was doing this a similar way to you: (You are only selecting one result from the database, if you were selecting many, this would be different.)
At top of page:
<?php
$email = $_SESSION['email'];
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$email."'");
while($row = mysqli_fetch_array($result)){
$member = $row;
}
mysqli_close($mysqli);
?>
then whenever you need to display the data in the page: (for example)
My username is <?php echo $member['username']; ?>
Maybe you should separate the query script (below) from the viewing part.
query.php
<?php
$result = mysqli_query($mysqli,"SELECT * FROM members WHERE email='".$_SESSION['email']."'");
while($row = mysqli_fetch_array($result)){
if($_SESSION['email'] == $row['email']) {
// If you find the right user with the same E-Mail address, DO SOME COOL THINGS :)
}
$returnArray[] = $row['username'];
$returnArray[] = $row['yourage'];
//and so on;
}
mysqli_close($mysqli);
?>
Some view.php (or index.html renamed to index.php):
<?php
include('query.php');
var_dump($returnArray);
//Or with a foreach or however
But you should learn about MVC Model View Controller and as others said, use OO programming
Learn ajax- this will help you separate this code from your application. Just make the ajax call to this php and get the result and show them how you want to show.
For example-
In a your application, say app.html, at the point you want to fetch something from db-
$.ajax({
type: "GET",
url: "fetch.php", // your aove php file
function(response){
console.log(response); // you'll get all the rows here
response=JSON.parse(response);
for(var i=0; i<response.length; i++){
console.log(response[i].username); // show results in view
....
}
}
});
fetch.php
$myrows = array();
while($row = mysqli_fetch_array($result)){
array_push($myrows, $row);
}
echo json_encode($myrows);
The reality is you want a templating engine of some sort to filter your database results directly into the template.
So rather than dealing with echo commands to design a page, you want a raw template and then to inject data into that template from your database array.
You can use something standardized like Mustache or roll your own fairly easily (although rudimentary):
$output = '';
$tpl = fopen('template.html','r');
$tpl = fread($tpl, 100000);
$templateVars = array();
while($row = mysqli_fetch_array($result)){
$temporaryRow = $tpl;
foreach ($row as $k=>$v) {
$temporaryRow = preg_replace("/{{$k}}/i",$v,$temporaryRow);
}
$output .= $temporaryRow;
}
echo $output;
And then your template.html could be something like
<div>Hello, {{username}}</div>
Related
// Page 1 - Code below works fine, but when I click the href link the
// variable I want is not sent to page 2.
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td> ' . $row['recipe_name'] . ' </td>
</tr>';
$recipe_name = $row['recipe_name'];
}
$_SESSION['recipe_name'] = $recipe_name;
echo '</table>'; // Close the table
?>
// Page2 - Code below receives the variable from page 1, but only the //last one in the table and not the one I clicked.
include ('core/init.php'); // Connect to the database
$recipe_name = $_SESSION['recipe_name'];
echo "My recipes is: ".$recipe_name."<br>";
?>
Try something like this using a get request.Since the users can see/alter the data, this is not the safest way of doing this but will do the job. Sessions are not involved in this technique.
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr><td>
' . $row['recipe_name'] . ' </td></tr>';
}
echo '</table>';
?>
// Page2
<?php
$recipe_name = $_GET['recipe_name'];
echo "My recipes is: ".$recipe_name."<br>";
?>
You are doing wrong in your page 2
Instead of session use $_GET['']; To get value from url we use $_GET.
Like this:
$recipe_name = $_GET['recipe_name'];
I hope this would help you.
This is my first attempt to write a very simple (one-file) blog-engine, build with PHP and MySQL. I want to make and have everything simple and don't want to include hundreds of files, classes and so on, because I just want to publish some text and that's is. I don't need plugins, changing templates, APIs or anything like that. The script is now working and running fine, but I'm a really novice and have just started with php/mysql. :)
So I want some feedback, what I've done wrong, what is maybe too complicated or if there is a possibility of injections or similiar? Any help and feedback is welcome (and sorry for my poor english!).
I've include some comments, so that's easier to follow my thoughts:
<?php
///////////////////////////////////////////////////// BASE
// Whats the name of the blog and how many recent articles should shown on the front
$blogname = 'The basic blogname';
$anzahl = '3';
// Alright, let's connect to the database
include_once 'include/connect.php';
// I use this to generate german date (e.g.: March --> März)
setlocale (LC_ALL, 'de_DE#euro.utf8', 'de_DE.utf8', 'de.utf8', 'ge.utf8');
///////////////////////////////////////////////////// START >>> IF
// As we using htaccess with modrewrite, we want to know, what page-name the user requested
if (isset($_GET['slug'])) {
// I'm not sure, if it makes sense (mysqli_/mysql_?) to avoid injections? Any help is welcome!
$blog = mysql_escape_string($_GET['slug']);
// Alright, now we check the database and ask if the sitename exist and if the status is "online" (published/draft)
$result = mysqli_query($con,"SELECT * FROM entries WHERE slug='$blog' AND status = 'ONLINE'");
// We call the result and check, if there is a article in the database
$num_results = mysqli_num_rows($result);
if ($num_results > 0){
// We now also include the header-file, because there we also have the $title-variable for the site / browsertab
include 'header.php';
include_once 'markdown.php';
// Create variables from the database-fields, also convert the content with markdown
while($row = mysqli_fetch_array($result)){
$title = $row['title'];
$content = $row['content'];
$my_html = Markdown($content);
$date = $row['date'];
$date = strftime('%d. %B %G', strtotime($date));
// and final: show the article on the website
echo '<h2>' . $title . '</h2>';
echo '<div id="date">' . $date . '</div>';
echo '<div id="content">' . $my_html . '</div>';
echo '<div id="link">Back to front-page</div>';
// we also inlucde the footer, so that we have a complete page - header/content/footer
include 'footer.php';
}
///////////////////////////////////////////////////// ELSE >>>
// but if there is NO entry in the database with this pagename...
} else {
// again we need the header
include 'header.php';
// then we say:
echo '<h2>Error</h2>';
echo '<div id="content">There is no article with this name!</div>';
echo '<div id="link">Back to front</div>';
// and include the footer
include 'footer.php';
}
///////////////////////////////////////////////////// ELSE >>>
// But if the user just open the blog and don't request a name, we want to show him the last articles (3 - see top)...
} else {
// So again we call the database and request the last published entries and sort them, limited by the amount of given entries
$result = mysqli_query($con,"SELECT * FROM entries WHERE status = 'ONLINE' ORDER BY id DESC LIMIT $anzahl");
// Again include header and markdown
include 'header.php';
include_once "markdown.php";
// We generate variables from the datebase during the loop, also convert the excerpt with markdown
while($row = mysqli_fetch_array($result)){
$title = $row['title'];
$slug = $row['slug'];
$excerpt = $row['excerpt'];
$my_html = Markdown($excerpt);
$date = $row['date'];
$date = strftime('%d. %B %G', strtotime($date));
// And publish them on the website
echo '<h2>' . $title . '</h2>';
echo '<div id="date">' . $date . '</div>';
echo '<div id="content">' . $my_html . '</div>';
echo '<div id="link">Read more...</div>';
}
// Last time, we include the footer again.
include 'footer.php';
}
///////////////////////////////////////////////////// <<< FINISH
?>
Thanks - and yes, I'm willing to learn! :))
By using SQL abstraction library and templates you can make your code more tidy
$sql = "SELECT * FROM entries WHERE slug=?s AND status = 'ONLINE'";
$row = $db->getRow($sql, $_GET['slug']);
if ($row) {
$title = $row['title'];
$content = Markdown($row['content']);
$date = strftime('%d. %B %G', strtotime($row['date']));
$tpl = 'single.tpl.php';
include 'main.tpl.php'
} else {
include '404.php';
}
and for the list
$sql = "SELECT * FROM entries WHERE status = 'ONLINE' ORDER BY id DESC LIMIT ?i";
$data = $db->getAll($sql, $anzahl);
$tpl = 'list.tpl.php';
include 'main.tpl.php'
Here is what i want to achieve ; sending ID's through URL's and printing it.
index.html
ID 1
ID 2
receive.php
<?php
$id_q = $_GET['id'];
print "The parameters passed through URL are $id_q";
?>
This above code works perfectly, I'm not able to do this with a list of ID's printed with a php command.
The below code is used to print all the PID's in the DB.How do i make every PID printed clickable ?
When I add html tags inside PHP code it throws up an error.
print.php
$result = mysqli_query($con,"SELECT * FROM List");
while($row = mysqli_fetch_array($result))
{
echo $row['PID'];
}
edit-query.php
$pid_q=$_GET[pid];
echo $pid_q;
while($row = mysqli_fetch_array($result))
{
echo "<a href='receive.php?id=".$row['PID']."'>".$row['PID']."</a>";
}
If you want to add your own text to a variable or echo, quote it and separate the variable with a "."
echo ''.$row['PID'].'';
you should do that like this
How about...
echo '' . $row['PID'] . '';
I believe this is what you mean?
while($row = mysqli_fetch_array($result))
{
echo 'Print ID: ' . $row['PID'] . '';
}
while($row = mysqli_fetch_array($result))
{
echo "<p id=".$row['PID']." class='clickable'>" . $row['PID'] . "</p>";
}
$(document).ready(function(){
$("#clickable").click(function(){
$(this)...something...
});
});
This is a little something you can do using JQuery if you wanted each PID to do something other than refer to another location. It will listen on any with the clickable class.
I want to pass php value in javascript. I run a query and apply if statement and while array on javascript. But always show empty result. I can't find the problem. anyone please help me. Thanks
<?php
session_start();
$SUserName=$_SESSION['view'];
include 'dbconnect.php';
$query="select * from user_permission where username='$SUserName'";
$result=mysql_query($query) or die (mysql_error());
?>
<script type="text/javascript">
d = new dTree('d');
d.add(0,-1,'Dhuronto');
<?php
if($SUserName=='sumon#dhuronto.com')
{
echo "d.add(1,0,'Admin','blank.php', 'Admin', 'main');";
}
else {
while ($row = mysql_fetch_array($result))
{
echo "d.add('$id','$pid','$node','$url', '$node', 'main');";
}
}
?>
</script>
Where are '$id','$pid','$node','$url', '$node' coming from?
while ($row = mysql_fetch_array($result))
{
echo "d.add('$id','$pid','$node','$url', '$node', 'main');";
}
Did you mean
while ($row = mysql_fetch_array($result))
{
echo "d.add('$row[id]','$row[pid]','$row[node]','$row[url]', '$row[node]', 'main');";
}
NB - i wouldn't use the above syntax myself, it being the only time you can write vars as $row[id]. I prefer
echo "d.add('" . $row['id']. "','" . $row['pid']. "'...
You are using the names of the columns as if they are variables. You need to get them from the array:
while ($row = mysql_fetch_array($result))
{
echo "d.add('{$row['id']}','{$row['pid']}','{$row['node']}','{$row['url']}', '{$row['node']}', 'main');";
}
Your code does not work because you have not defined values for $id, $pid, and so on. That said, you can use json_encode() to JavaScript encode PHP data types properly, assuming your text is UTF-8 encoded:
while ($row = mysql_fetch_array($result))
{
// I don't know your database schema, so this could be wrong
$args = array(
$row['id'], 0, htmlspecialchars($row['username']),
'blank.php', '', 'main'
);
// echo 'd.add.apply(d,' . json_encode($args) . ');';
echo 'd.add(' . implode(',', array_map('json_encode', $args)) . ');';
}
Note that dTree is sort of an outdated JavaScript library that has fallen behind current best practices. It was last updated in 2003! You might want to look into newer, better alternatives such as those mentioned at https://stackoverflow.com/questions/1710114/jquery-tree-plugin.
Hey, I have been trying to get this pagination class that I am using to be more ajaxy - meaning when I click on the page number like page [2] the data loads, but I want to load in the data without going to a different page (HTTP request in the background, with no page reloads).
Being new to both php and jquery, I am a little unsure on how to achieve this result, especially while using a php class.
This is what the main page looks like by the way:
<?php
$categoryId=$_GET['category'];
echo $categoryId;
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery_page.js"></script>
<?php
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost', 'root', 'root');
mysql_select_db('ajax_demo',$conn);
$sql = "select * from explore where category='$categoryId'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1¶m2=value2');
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
echo "<table width='800px'>";
while($row = mysql_fetch_assoc($rs)) {
echo "<tr>";
echo"<td>";
echo $row['id'];
echo"</td>";
echo"<td>";
echo $row['site_description'];
echo"</td>";
echo"<td>";
echo $row['site_price'];
echo"</td>";
echo "</tr>";
}
echo "</table>";
echo "<ul id='pagination'>";
echo "<li>";
//Display the navigation
echo $pager->renderFullNav();
echo "</li>";
echo "</ul>";
?>
<div id="loading" ></div>
<div id="content" ></div>
Would I need to do something with this part of the class?, as seen above:
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1¶m2=value2');
Or this?:
echo $pager->renderFullNav();
I don't no much about jquery,but i guess I would start it like:
$("#pagination li").click(function() {
Then load something maybe...
I don't no. Any help on this would be great. Thanks.
Im not sure how to go about it using that class, it seems it would be a bit tricky, as the script you make the ajax call to, to retrieve the data, will need to have access to the current PS_pagination instance.
Without the class though, it wouldnt be too tricky.
You would need a php script to actually return the data, which takes in the number of records per page, and the current page number. In this script, rather than returning the data, i return the html. So i take the data from the database, then generate the table. This means that all i have to do on success of ajax is replace what is in the able currently, with the new html that i get from this script. Heres an example..
//Current Page Number
$page_num = isset($_GET['page_number']) ? mysql_real_escape_string($_GET['page_number']) : 1;
//Number of records to show on each page
$num_records = isset($_GET['num_records_pp']) ? mysql_real_escape_string($_GET['num_records_pp']) : 10;
//Row to start collecting data from
$start_row = $num_records * ($page_num - 1);
//String to store html to return
$return_html = '';
//SQL Query
$sql = mysql_query("SELECT * FROM my_table LIMIT $start_row, $num_records");
//Query success
if($sql) {
//Construct html for table
$return_html = "<table width='800px'>";
while($row = mysql_fetch_array($sql) {
$return_html .= "<tr>";
$return_html .= "<td>" . $row['id'] . "</td>";
$return_html .= "<td>" . $row['site_description'] . "</td>";
$return_html .= "<td>" . $row['site_price'] . "</td>";
$return_html .= "</tr>";
}
$return_html .= "</table>";
//Query Failed
} else {
$return_html = "<p class='error'>Error Fetching Data</p>";
}
return $return_html;
Then you just make a get request via ajax and pass the page number, and the number of rows you want.
$.get("get_data.php", { page_number: 1, num_records_pp: 20 },
function(data){
$('div#my_table').html(data);
});
So, this query assumses that you have a div with an id of "my_table" which contains your table, it will then replace this with a new table consistion of just the data you requested.
This code was just to give you the jist, so i may have some errors in there, but hope it helps.