Im making a list with names and links to full info about them. So, I've got simple search engine, which searching by the names or specific numbers. I use $_SESSION to get id of the people. The problem is, when there are more than 1 name and Im moving to the page of specific person appears the page of the last person in the list!
So, code of the search engine is:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9_a-z A-Z]#i","",$searchq);
$query = mysql_query("SELECT * FROM contract WHERE name LIKE '%$searchq%' OR student_code LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no such results!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$student_code = $row['student_code'];
$_SESSION['users_id'] = $row['users_id'];
$output = '<table border ="1"><tr><td>'.$name.' '.$student_code.'
</td>
<td>
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
</form>
</td>
</tr>
</table><br \>
And another script in the page file:
$users_id = $_SESSION['users_id'];
$result = mysql_query("SELECT * FROM contract WHERE users_id = $users_id");
while($myrow = mysql_fetch_array($result)){
$output1 =
The way I understood your question is that you have two pages. One page that does the search, and another page that show the "more info" about a specific result.
What you're basically doing in the search is this:
Let's assume you have three results that got Id 1,4,7.
This is what's going to happen in your while loop
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 1)
Prepare the first result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 4)
Prepare the second result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 7)
Prepare the third result
As you can see you're always overwriting the session key and therefore only the last one will be available when you get to the "cont.php" page (where I'm guessing the other code is?)
One simple solution would be to bake the id into the form and send it along in the request to the cont.php page. Something like this:
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
<input type="hidden" name="user_id" value="' . $row['users_id'] . '">
</form>
And then in the cont.php you simply change this:
$users_id = $_SESSION['users_id'];
to this
$users_id = $_POST['users_id'];
Hope that helps :)
Related
In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
I have just started trying to learn PHP and MYSQL and have been following some tutorials for creating a webpage search engine, but have been experience an issue wherein when i submit the form the results aren't returned, i have no idea as to where the problem lies or where to try and troubleshoot it, so it thought it'll be worth a shot to post my problem here. Hopefully someone can help me out, thanks in advance.
PHP
<?php
mysql_connect("localhost","root","123")or die("Could not connect to Db");
mysql_select_db("members") or die("Could not find db");
if(isset($_POST['submit'])){
$searchq = $_POST['submit'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq%' ") or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output = "No results were found, sorry.";
}
else{
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
}
}
?>
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="searchfname" placeholder="Enter first name">
<input type="text" name="searchlname" placeholder="Enter last name">
<input type="submit" name="submit" value="Submit">
</form>
<?php print($output);?>
</body>
</html>
You can use $_POST['submit'] to check if the form was submitted, but it does not hold all the form values.
You can access the separate form values by their respective name.
So use $_POST['searchfname'] for the value in the first textbox and $_POST['searchlname'] for the second.
Your code should read more like this;
$searchqf = $_POST['searchfname'];
$searchql = $_POST['searchlname'];
$searchqfreplace = preg_replace("#[^0-9a-z]#i","",$searchqf);
$searchqlreplace = preg_replace("#[^0-9a-z]#i","",$searchql);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchqf%' OR Lname LIKE '%$searchql%' ") or die(mysql_error());
$count = mysql_num_rows($query);
Notice that this way of composing queries is very insecure and vulnerable for SQL injection.
You're also asking for a way to troubleshoot. You probably want to look into echo and print_r.
You have assigned the $searchq variable to your submit button.
Change this line
$searchq = $_POST['submit'];
to
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
or both:
$searchq = $_POST['searchfname'].$_POST['searchlname'];
you cannot use $searchq = $_POST['submit']; since no value is being posted whose name is submit
you must use any of the following....
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
In your code you are searching for 'submit' value instead of values from form.
Replace $searchq = $_POST['submit']; with:
$searchq = $_POST['searchfname'];
$searchq2 = $_POST['searchlname'];
and query:
Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq2%'
Firstly,
either search with searchfname or with searchlname or both.
Secondly, modify like this
after $count = mysql_num_rows($query);,
if($count == 0){
$output = "No results were found, sorry.";
}
else{
$output = '';
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
Thirdly, Use print $output in the Second page(where database is fetched) and not in First page(Page with FORM).
If you want to show result in the First page, use jQuery/Ajax function
I'm working on a small board/forum. I have topic posting done; it's visible in the database and all that jazz. Now I'm working on retrieving the topic list and so that when you click a topic you can view it. That's working fine, except that when I click on it the page goes blank and nothing is being shown. I know the issue is that I can't get the id of the post I clicked on because it's in the if-else statement with a while loop. Here is my code now.
<?php
require('init.php');
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
if (!isset($_GET['view_thread'])) {
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
while ($select_threads = mysql_fetch_assoc($get_threads)) {
$title = $select_threads['title'];
$time = $select_threads['time'];
$user = $select_threads['user'];
$id = $select_threads['id'];
$form = '<center>
<form method="get" action="">
<input type="submit" name="view_thread" id="view_thread" value="'.$title.'" />
<input type="hidden" name="thread_id" id="thread_id" value="'.$id.'" />
</form>
</center>';
echo '<div id="post_info">'.$form.'<hr>Posted by: <b>'.$user.'</b> '.$time.'</div>';
}
} else {
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$id'");
$select_posts = mysql_fetch_assoc($get_posts);
$content = $select_posts['content'];
echo $content;
}
?>
I need to get that $id so I can grab the post and later all the replies from the database. I'm new to php so I'm probably missing something. Thanks for any help!
first: your parameter is named "thread_id", so your query should be
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$thread_id'");
BUT i strongly suggest to
go for POST instead of GET
use mysql_real_escape to avoid SQL injection