php loop values - mysql lookups - php

I'm trying to create a user profile page. The user selects whose profile he wants to view based on a search. By clicking a "view profile" button the page should then go to profile.php where it displays the user's profile.
For now, I'm just trying to test it out and only display the user's name. Here's the code I have.
My problem is that I don't know how to pass "$userID" to profile.php which will then be used to look up that user's information. Since the value is in a while loop, I'm not sure how to select for once instance of this loop.
function findUsers($friend){
$search = mysql_query("Select * from users where username='$friend'");
$userLocation = mysql_query("select * from userinfo where username='$friend'");
$locationResult = mysql_fetch_array($userLocation);
$locationResultArray = $locationResult['userlocation'];
$locationExplode = explode("~","$locationResultArray");
//table column names
echo "<table>";
echo "<tr><td>";
echo "Username";
echo "</td><td>";
echo "Location";
echo "</td></td><tr><td>";
while($result = mysql_fetch_array($search)) //loop to display search
{
$userID = $result['userid']; //can I pass this value to the function since it's possible that there is more than 1 userID from the while loop?
echo $result['username'];
echo "</td><td>";
echo $locationExplode['0'];
echo ", ";
echo $locationExplode['1'];
echo "</td><td>";
?>
<form method="post" action="profile.php">
<?
echo "<input type='submit' name='profile' value='View User's Info'";
echo "</td><td>";
?>
</form>
<form method="post" action="profile.php">
<?
echo "<input type='submit' name='addfriend' value='Add Friend' />"; //code still needs to be written for this input.
echo "</td></tr>";
}
echo "</table>";
if(isset($_POST['profile'])){
$viewProfile->displayProfile($userID); //This is where I'm not sure if it's taking the correct userID.
}
}
}
?>
...and the page to display the profile
<?
include_once 'infoprocesses.php';
$user = new dbProcessing();
Class viewProfile{
function displayProfile($username){ //display profile pulls the user's name from the databse
echo $username; //used to test if value is being sent...nothing is being displayed
?>
<h2><?php $user->username($username);?>'s Information</h2>
<?
}
}
?>

Normally, I will make it as a link with the friend's userid passed as GET variable.
Something like this
echo "<a href='profile.php?userid=" . $result['userid'] . "'>". $result['username'] ."</a>";
For your current design, your options are:
set the action to
<form method="post" action="profile.php?userid=<?php echo $result['userid']; ?>">
or
make a hidden input field with the friend's userid.
<input type='hidden' name='userid' value='<?php echo $result['userid']; ?>' />
The first method is passing as POST variable, then you can retrieve from $_POST['userid'] while in the second method, you will retrieve from $_GET['userid'] variable.

while($result = mysql_fetch_array($search)) //loop to display search
{
echo $result['username'];
echo "</td><td>";
echo $locationExplode['0'];
echo ", ";
echo $locationExplode['1'];
echo "</td><td>";
echo 'View User's Info';
}
echo "</table>";
}
and in the profile.php just
$userid = $_GET['id'];

Related

Echo the selected items in drop down menus

I created two dropdown menu populated by two different database tables. I also created a button to press after having chosen something from the menu. What I would like to do (but I am not able to) is to print on the screen the selected items. Below the code I wrote until now:
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";echo "<body>";echo "<form action='index.php'>"; echo "Select your Departure: <select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />"; echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>
You are trying to retrieve data by $_POST data. but in form you haven't specify request method. So it will take get method by default. So you need to specify method=post in form to get request from POST
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";
echo "<body>";
echo "<form action='index.php' method='post'>";
echo "Select your Departure:
<select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />";
echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>

SQL insert query loop

Hello so i am doing this school assigment where i have make a comment system corresponding to the post ID and i know that it looping three times but i gave it the post id. And i know that the postID is changeing all the time. i just have no idea how to fix this bug any ideas?
<?php require_once("menu.php");
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
if (!empty($_POST['comment']) ) #To insert new comments in the database
{
$comment = $_POST['comment'];
$userid = $_SESSION['userID'];
$insertCommentQuery = "INSERT INTO `tblcomments` (`Content`,`UserID`,`PostID`,`Timestamp`) VALUES ('$comment','$userid','$postid',CURRENT_TIMESTAMP)";
$resultComment = mysqli_query($connection, $insertCommentQuery)
or die("Error in the query: ". mysqli_error($connection));
}
echo "<div class=\"wrapper\">";
echo "<div class=\"titlecontainer\">";
echo "<h1>$row[Title]</h1>";
echo "</div>";
echo "<div class=\"textcontainer\">";
echo "<span>$row[Content]</span>";
echo "</div>";
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>">
</div>
<?php
}
echo "<div class=\"timestampcontainer\">";
echo "<b>Date posted :</b>$row[TimeStamp] ";
echo "<b>Author :</b> Admin";
echo "</div>";
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
echo "<div class=\"commentcontainer\">";
echo "<div class=\"commentusername\"><h1>Username :$commentRow[Username]</h1></div>";
echo "<div class=\"commentcontent\">$commentRow[Content]</div>";
echo "<div class=\"commenttimestamp\">$commentRow[Timestamp]</div>";
echo "</div>";
}
if (!empty($_SESSION['userID']) )
{
echo "<form method=\"POST\" action=\"\" class=\"post-frm\">";
echo "<label>New Comment</label>";
echo "<textarea id=\"comment\" name=\"comment\"> </textarea>";
echo "<input id=\"submit\" type=\"submit\" name =\"submit\" class=\"button\"/>" ;
echo "</form>";
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Well, that's exactly what your script does. It queries all posts, loops through them, and then performs an insert for all of them. To fix this, store the id of the post in the comment form. When you post the form, insert just a single comment and use the id in the form.
That could look something like this:
<?php
if (array_key_exists('postid', $_POST))
{
$postid = $_POST['postid'];
$comment = $_POST['comment'];
// Perform a single insert here, and use $postid and $comment.
}
// Then, start rendering the page:
require_once(menu.php);
$connection = connectToMySQL();
$selectPostQuery = SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC;
$result = mysqli_query($connection,$selectPostQuery)
or die(Error in the query: . mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
// Render the post itself here.
?>
<div class="wrapper">;
<div class="titlecontainer">;
<h1><?=$row['Title']?></h1>;
</div>;
<div class="textcontainer">;
<span><?=$row['Content']?></span>;
</div>;
<?php
// Render a comment form for each post (is that what you did?)
if (!empty($_SESSION['userID']) )
{?>
<form method=POST action= class=post-frm>
<label>New Comment</label>
<textarea id=comment name=comment></textarea>
<input type=hidden name=postid value=<?=$postid?>/>
<input id=submit type=submit name =submit class=button/>
</form>
<?}
}
Most of your code is the same, only the processing of the post data is now done before the loop.
Otherwise, I just fixed some small syntactic things (and maybe introduced new ones, I haven't tested it).
Also, I took the HTML out of echoes. It's a matter of taste, of course, but experience has taught me that big chunks of HTML in echo statements isn't very readable or maintainable. Rather just close the PHP tags, output the raw HTML and echo only the variables in it. You can use the short notation for that: <?= $value ?>, which basically means <?php echo $value ?>.

get a variable row from a while mysql_fetch array that isnt the last result

Hey guys I'm having a hard time sending a session variable of the $row['projectnaam']
that belongs to the one that just has been clicked.
At the moment the Session always takes the last $row['projectnaam']
from the while loop and I'm wondering how I can send the right
variable with a session that belongs to the row that just has been clicked.
Thank you in advance.
Here's my syntax:
<?php
include "config.php"
$bedrijfsnaam = $_SESSION['gebruikerbedrijf'];
$result= mysql_query("SELECT * FROM projecten WHERE bedrijfsnaam='$bedrijfsnaam' ")or die(mysql_error());
while($row = mysql_fetch_array($result)){
if (isset($_POST['submit'])){
$_SESSION['projectnaam'] = $projectnaam;
header('Location: viewprojectsbedrijf.php');
}
echo "<div class='project'>";
echo "<div class='projectdetails'>";
echo "<p class='projectnaam'>";
echo $row['projectnaam'];
echo "</p>";
echo "<hr class='paars'>";
echo "<p class='datum'>";
echo $row['datum'];
echo "|";
echo $row['Tijd'];
echo "</p>";
echo "<hr class='paars'>";
echo "<p class='bedrijfsnaam'>";
echo $row['bedrijfsnaam'];
echo "</p>";
echo "</div>";
echo "<div class='view'>";
echo "<form method=\"POST\" action=\"\">";
echo "<input type='submit' value='View' name='submit' class='viewbutton'></input>";
echo "</form>";
echo "</div>";
}
?>
Mede Nederlander ;)
I think you mean to do something like this:
include("config.php");
if(isset($_POST['submit'])){
$_SESSION['projectnaam'] = $_POST['projectnaam'];
header('Location: viewprojectsbedrijf.php');
}
$bedrijfsnaam = $_SESSION['gebruikersbedrijf'];
$result= mysql_query("SELECT * FROM projecten WHERE bedrijfsnaam=".$bedrijfsnaam)or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<div class='project'>
<div class='projectdetails'>
<p class='projectnaam'>
<form method=post action=''>
<input type=text value=".$row['projectnaam']." name=projectnaam>
</p>
</div>
</div>
<input type='submit' value='submit' name='submit'>
</form>";
}
In your own script only your submit button is in the form, so that will be the only value posted. In that case you won't get the POST value of 'projectnaam'.
Also, you try to make a SESSION value of a variable which isn't declared in your posted code. In my code it makes a Session value of the POSTED code.

Submit form of Iframe from the parent window

<iframe id="frame1" name="frame1" align="center" src="committee_assign1.php" height="400" width="700">
</iframe>
<center><input onClick="submitiframeform(); return false;" type="button" name="submit" value="Submit" />
<script type="text/javascript">
function submitiframeform(){
window.frames['frame1'].document.forms['fypassign'].submit();
}
</script>
The above is the main page name committee_assign.php ..
And below is the page where the iframe called committee_assign1.php.
<?php
include '../database.php';
include 'valid_login.php';
if(isset($_POST['submit'])) {
$continue = FALSE;
$i = 0;
while ($continue == FALSE) {
if (isset($_POST['id_'.$i])) {
$fypcomm = $_POST['fypcomm_'.$i];
$user = $_POST['id_'.$i];
$sql = mysql_query(" UPDATE Lecturer SET LectFypCommittee = '$fypcomm' WHERE LectID = '$user' ")
or die(mysql_error());
mysql_query($sql);
} else
{$continue = TRUE;}
$i++;
}
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='../committee/committee_assign1.php'
</SCRIPT>");
}
?>
<head>
</head>
<body>
<form id="fypassign" name="fypassign" method="post" action="" target="_self" onSubmit="">
<?php
$counter = 0;
echo "<table class ='box'>";
echo "<thead>";
echo "<tr>";
echo "<th align='left' valign='top'>"."Lecturer Name"."</th>";
echo "<th align='left' valign='top'>"."FYP Committee"."</th>";
echo "</tr>";
$sql = mysql_query(" SELECT * FROM Lecturer ORDER BY LectFypCommittee DESC, LectName ASC ") or die(mysql_error());
while($info = mysql_fetch_assoc($sql)) {
$idcount = "id_".$counter;
echo "<input type='hidden' name='$idcount' id='$idcount' value={$info['LectID']} />";
echo "<tr>";
echo "<td>";
echo $info['LectName'];
echo "</td>";
echo "<td>";
$formname = "fypcomm_".$counter;
echo "<select name='$formname'>";
//to convert the flag value to user understandable language
if ($info['LectFypCommittee'] == '0'){
$dbfyp = 'No';
}
else $dbfyp = 'Yes';
echo "<option selected='selected' value='{$info['LectFypCommittee']}'>".$dbfyp."</option>";
if ($info['LectFypCommittee'] == '0'){
echo "<option value='1'>".'Yes'."</option>";
}
else echo "<option value='0'>".'No'."</option>";
echo "</select>";
echo "</td>";
echo"</tr>";
$counter++;
}
echo "</table>";
?>
</form>
</body>
I clicked submit button at the parent page and the page refresh but the value is not update.
Can anyone here guide me on this please?
So sorry to post such long codes as I hope you guys could understand more what I am doing. TQ
You have no input in your committee_assign.php named submit:
if(isset($_POST['submit']))
You must check with something like this:
if(isset($_POST))
You are checking if submit has been posted but you dont have an input named submit. Add an input named submit with some value and check if that post submit exists. You can make it hidden if you dont want to see an extra input.
if($_POST['submit']) is checking if there is a value with key 'submit' in the post array. All the key and value in $_POST array is name and value of a form element respectively.

Passing dropdown list value to another SELECT statement on same page

Hi and thanks for looking at this with me. I am COMPLETELY new to using PHP to run MySQL select statements. That being said, I have managed to run a SELECT statement to populate a drop down list...and another SELECT statement to populate an HTML table. (this is for a roleplaying game)
But this is where3 I get stuck...
I would like for the dropdown selected value to be the "WHERE racename = " value in the second select statement that populates the table so that only one row is returned instead of all the data.
Here's the page: http://www.gamehermit.com/racechoice.php
Here's my code so far:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "db_username", "password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query="SELECT * FROM Races";
$result = mysql_query($query);
echo "<select name=racename>";
while($nt=mysql_fetch_array($result))
{
if ($nt[racename]==$_POST["racename"])
$selected="selected";
else
$selected="";
echo "<option ".$selected."value=$nt[racename]>$nt[racename]</option>";
}
echo "</select>";
echo "<br />";
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT * FROM Races")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Race Name</th> <th>Might Modifier</th> <th>Valor Modifier</th> <th>Deftness
Modifier</th> <th>Insight Modifier</th> <th>Dweomer Modifier</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['racename'];
echo "</td><td>";
echo $row['modmight'];
echo "</td><td>";
echo $row['modvalor'];
echo "</td><td>";
echo $row['moddeftness'];
echo "</td><td>";
echo $row['modinsight'];
echo "</td><td>";
echo $row['moddweomer'];
echo "</td></tr>";
}
echo "</table>";
?>
I hope this is simple...thanks so much :)
~ Jack
The best way to do so is to use AJAX so you don't need to pass variables and load a new page.
But here's how you can do it with the old-fashioned way:
assume you will be having only one page and you will pass the selected value to the same page (a page reload is required)
so let's say your page is game.php
you need to include in this page a "jump menu" with a submit button to be pressed after the user selects something from the list
in the header of your page you need to check if the button was pressed using the
if(isset($_POST['button_name'])) {
// button pressed.. perform next step and select your new data to fill the table
} else {
// nothing pressed and nothing to be performed load the page normally
}
inside the "true" of the "if" you need here to get the passed variable from the list for example
$var = $_POST['list_name'];
so now you have the second variable to select the required data to fill the table.
a complete code should look something similar to the following, game.php:
<?php
if(!isset($_POST['go_button'])){ //option not selected display list to choose from
// Make a MySQL Connection
mysql_connect("localhost", "db_username", "password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query="SELECT * FROM Races";
$result = mysql_query($query);
$num = mysql_numrows($result);
?>
<script type="text/javascript">
function MM_jumpMenuGo(objId,targ,restore){ //v9.0
var selObj = null; with (document) {
if (getElementById) selObj = getElementById(objId);
if (selObj) eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0; }
}
</script>
<form name="form" id="form" action="game.php" method="post">
<select name="jumpMenu" id="jumpMenu">
<?php $i=0; while($i<$num) { ?>
<option value="<?php echo mysql_result($result,$i,'racename_field_value'); ?>"><?php echo mysql_result($result,$i,'racename'); ?></option>
<?php } ?>
</select>
<input type="button" name="go_button" id= "go_button" value="Go" onClick="MM_jumpMenuGo('jumpMenu','parent',0)">
</form>
<?php
echo "<br />";
} else { //option selected to get the variable and use it to select data from DB
$var= $_POST['jumpMenu'];
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT * FROM Races WHERE racename='$var'")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Race Name</th> <th>Might Modifier</th> <th>Valor Modifier</th> <th>Deftness
Modifier</th> <th>Insight Modifier</th> <th>Dweomer Modifier</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['racename'];
echo "</td><td>";
echo $row['modmight'];
echo "</td><td>";
echo $row['modvalor'];
echo "</td><td>";
echo $row['moddeftness'];
echo "</td><td>";
echo $row['modinsight'];
echo "</td><td>";
echo $row['moddweomer'];
echo "</td></tr>";
}
echo "</table>";
}
?>
I modified your code and added something to get you start with, excuse me if there was any error when trying to load the page i wrote it without trying it
good luck!

Categories