// 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.
Related
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>
I am having an issue getting the $userid from $_POST. I have done this lots of times before, so I am not sure what I am doing wrong all of a sudden.
Form that is submitting to user_confirm.php
<?php
//confirm user function
function confirmUsers() {
//make connection global
global $con;
//set user variables
$userquery = mysqli_query($con, "SELECT * FROM users WHERE userlevel = 0");
//echo list
echo '<center><form name="userConfirm" action="functions/user_confirm.php" method="post">';
echo '<select name="confirmUser">';
while ($row = mysqli_fetch_array($userquery)) {
echo "<option value='" . $row['userid'] ."'>" . $row['username'] ."</option>";
//in viewing element, the userid is displaying properly
}
echo '<input type="submit" value="Confirm User">';
echo '</select>';
echo '</form></center>';
}
?>
user_confirm.php
<?php
//include db connect
include ("db_con.php");
//set variable names
$userid = $_POST['userid'];
//start session
session_start();
echo $userid;
?>
As you can see, I am simply just trying to echo the variable passed from the form. It is not working and I am totally confused as to why, any ideas?
in case it was needed here is db_con.php
<?php
$con=mysqli_connect("localhost","user","pw","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You dont have a form field called userid, perhaps you mean the confirmUser field:
$userid = $_POST['confirmUser'];
You are not passing the userid var to user_confirm.php, try renaming your select to userid
The coding looks right to me and should work.
I'm not sure if this will help but try to load the session_start(); first.
The next thing would be to do a print_r($_POST) and see what shows.
Also view the source of the finished html and see how it prints out.
Also I like to use
echo <<
END;
With this you can just type in the html plus the strings with no ' or " unless the html needs it.
I missed the confirmUser myself.. =(
I'm trying to get data from a database if a link is clicked.
I used the example codes suggested from this example -Getting mysql field data when a link is clicked?
But it doesn't work when I click on a link nothing comes up.
main.php
<?php
include('conn.php');
$sql2 = "SELECT Title FROM addpromo";
$result2 = mysql_query($sql2);
echo "<div id=\"links\">\n";
echo "<ul>\n";
while ($row2 = mysql_fetch_assoc($result2)) {
echo "<li> <a href=\"fullproject.php?title=\""
. urlencode($row2['Title']) . "\">"
. htmlentities($row2['Title']) . "</a>\n</li>";
}
echo "</ul>";
echo "</div>";
?>
This is displaying correct.but when I click at a link nothing is showing up in fullproject.php, Just a blank page.
fullproject.php
<?php
// Connect to server.
include('conn.php');
$projectname = isset($_GET['Title']);
$sql1 = "SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title'] . "<br />";
echo "<br /> ";
}
?>
Can someone help me to fix this, or any other way to make this(to get data from a database if a link is clicked) possible?
Change to this
main.php
<?php
include('conn.php');
$sql2="SELECT Title FROM addpromo";
$result2=mysql_query($sql2);
echo '<div id="links">';
echo '<ul>';
while($row2 = mysql_fetch_assoc($result2)){
echo '<li>'.htmlentities($row2['Title']).'</li>';
}
echo '</ul>';
echo '</div>';
?>
fullproject.php
<?php
if(isset($_GET['title'])){
include('conn.php');
$projectname= $_GET['title'];
$sql1="SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title']. "<br />";
echo "<br /> ";
}
}
?>
This is storing a boolean value $projectname= isset($_GET['Title']);, whether or not the title is set. Instead use $projectname = $_GET['Title'];
isset returns a boolean value (true/false) and you want the actual value of the variable:
$projectname= $_GET['title'];
Furthermore, you have to pass only the title as the URL parameter, without enclosing it within quotes. So there is an error in this line:
echo "<li> <a href=\"fullproject.php?title=" . urlencode($row2['Title']) . "\">"
Note the lack of \" after title=
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.
This may be an easy fix, but I can't get my head around it .
Basically I've remade my blog using a database and php rather than wordpress.
I want my site to show the most recent post first, then i'm using PhP postback to alter it
So far it works, but i can't figure out a way for it to automatically go to the most recent one but then change after the postback.
<?php
$inId = $data[0];
//if (!empty($inId))
//{
//}
//else
//{
//$inId = $_POST['ID'];
//}
include 'Includes.php';
$blogPosts = GetBlogPosts($inId);
foreach ($blogPosts as $post)
{
echo "<div class='post'>";
echo "<h3>" . $post->title . "</h3>";
echo "<p2>" . $post->post . "</p2>";
echo "<span class='footer'>Posted By: " . $post->Author . " Posted On: " . $post- >datePosted . "</span>";
}
echo '<form name="myForm" action="Index.php" onsubmit="return validateFormStrings()" method="post">';
echo'<select name ="ID">';
$query4 = "SELECT * FROM Blogs ORDER BY ID ";
$result = mysql_query($query4);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<option value="'.$row['ID'].'">'.$row['Title'].'</option>';
echo '<br>';
}
echo'</select>';
echo '<input type="submit" value="Retrieve Posts">';
echo '<a href="Index.Php" ></a>';
echo '</form>';
?>
As you see i tried to fiddle with !empty and things but that's not really what im trying to do.
If i'm unclear let me know.
I almost need something like " if ( button !pressed) then its data[0] else its the postback
Thanks in advance
I found out how to do it using the isset() function.
if (isset($_POST['submit1']))
{
$inId = $_POST['ID'];
}
else
{
$inId = $data[0];
}
This checks if the submit button has doe the postback or not. Works a treat.
Gonna have a go at trying it with Ajax so I don't need the button at all ^^