php - send variable to next page by link - php

I need help.
How can I call the variable(within the url) after a successful search result in my index.php to the next page view.php so that I can view the complete data of the variable?
heres my code
"index.php"
<form method="post" action="index.php?go" id="searchform">
<input type="text" name="name" size = "50">
<br/>
<input type="submit" name="submit" value="SEARCH">
<button type="reset" value="Reset">RESET</button>
</form>
<?php
$db=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("emp_dbA");
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['name'])){
$name=$_POST['name'];
$letter=$_GET['by'];
$sql="SELECT emp_ID, fname, lname,mname FROM emp_tbl WHERE fname LIKE '%" . $name . "%' OR lname LIKE '%" . $name ."%' OR mname LIKE '%" .$name . "%'";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
echo "<p>" .$numrows . " results found for " . stripslashes($name) . "</p>";
while($row=mysql_fetch_array($result)){
$fname =$row['fname'];
$mname =$row['mname'];
$lname=$row['lname'];
$ID=$row['emp_ID'];
echo "<ul>\n";
echo "<li>" . "" .$fname . " " . $mname. " " . $lname . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>

You can use GET or POST to send data to the next page.
http://www.tizag.com/phpT/postget.php

By using the reserved variable $_GET
$_GET['id']
REFERENCE

You get the URL parameters with the $_GET environment variable, while the field you did put inside the form (given that you chose post as the form method) will be read like $_POST["name"].
As a little piece of advice, try to resort to the GET method as few times as possible. Parameters received with the GET method are seen in the URL, while parameters received from the POST method aren't.
And, of course, sanitize all your GET/POST data before actually using it.

$_SERVER['PHP_SELF'] might be a good use here if you want to handle this data on your index.php page. If you'd like to pass it to view.php, action should be:
<form action="view.php" method="POST"></form>

Why not use a pagination class? Look this: http://phpsnaps.com/snaps/view/php-pagination-class/ PS. mysql is deprecated, use mysqli.

Related

PHP loop generated buttons - only last one works?

First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.
You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}
You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()
Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.

$_POST Array issue PHP MySQL

First of all, I am a newbie when it comes to coding, so please be kind and patient :)
What I am trying to do is to select two rows ('ID', 'name') from a MySQL table (categories), populate a drop down list with one row ('name'), and on submission of a form, pass the other ('ID') to another table.
Now, I can populate the drop down list, no problem. I have populated this with both 'ID' and 'name' to test that both of the variables I am using to hold this information, contain the correct data. But I cannot seem to $_POST the information.
I guess I am either looking at the wrong part of the array, or I am simply using the wrong code.
This is the code to create a new product, under a category from the database.
<?php
include 'db_config.php';
?>
<form enctype="multipart/form-data" action="insert.php" method="post">
<h3>Add New Product</h3>
Category:
<!-- START OF categories (table) names (row) SQL QUERY -->
<? $sql = "SELECT ID, name FROM categories";
$result = $mysqli->query($sql);
echo "<select name='category_name'>";
while ($row = $result->fetch_assoc()) {
$cat_ID=$row['ID'];
$cat_name=$row['name'];
extract($row);
echo "<option value='" . $cat_ID . $cat_name . "'>" . $cat_ID . " " . $cat_name ."</option>";
}
echo "</select>";
?>
<!--END OF SQL QUERY -->
<br>
Code: <input type="text" name="code"><br>
Name: <input type="text" name="prod_name"><br>
Description: <input type="textarea" name="description"><br>
Image: <input type="file" name="image"><br>
<input type="Submit">
</form>
For now, I am just echoing this out in the insert.php script, to test the code above. This is a snippet of the insert.php script.
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
echo "Code: ". $_POST['code'] . "<br>";
echo "Name: " . $_POST['prod_name'] . "<br>";
echo "Description: ". $_POST['description'] . "<br>";
echo "Image: " . $_POST['image'] . "<br>";
Don't worry about the last line above. I know this needs to be $_FILES, and I have all this covered. I have stopped writing the data to the table until I get my issue fixed. In the full script, image are being upload to "/images" and the location stored in the table. This all works fine.
The problem is with the first two lines, as they are blank when returned. I thought I was storing the information correctly, as I am calling the same variables to populate the drop down list, but I cannot seem to $_POST it.
Does that makes sense?
Thanks to all who help me. Once day I will be as good as you....I hope.
TIA
Smurf.
this bellow:
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
is wrong, select element has its name category_name, so, instead of this, you should
do:
echo "Category: " . $_POST['category_name'] . "<br>";
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
There aren't any form elements with those names in your form ($row["ID"] and $row["name"]). Those would be really strange names for a form element anyway. The form element you're creating is:
<select name='category_name'>
So the selected value would be posted as:
$_POST['category_name']
The option elements for that select appear to have values which are a combination of ID and Name:
"<option value='" . $cat_ID . $cat_name . "'>"
Thus, if the user selects an option with a value of 1SomeName then $_POST['category_name'] will evaluate to '1SomeName'.
It's certainly unconventional to use the combination of ID and Name for the option values, but it should work. The problem is presents is that you now have a composite string which needs to be parsed in order to be useful. Generally what one would do is just use the ID as the value and the Name as the display. All you should need to use it throughout the code is the ID.
The $_POST variable you want, is inside category_name
Cuz your select is...
<select name='category_name'>
So you need to get it by...
$_POST['category_name'];
Which will return whatever you've assigned to the select options...ie
2 Name
2 being the ID, and Name being the name
But if you then want to use that ID to retrieve from DB or anything, you're gonna have to explode that apart...like so....to get each piece.
$array = explode(" ", $_POST['category_name']);
That will leave you with...
$array[0] = ID
$array[1] = Name
But I would avoid all that part, by just assigning the ID to the value only...like so..
echo "<option value = '".$cat_ID."'> ".$cat_name." </option>";
That way you just pass the ID and have access to it on the other side.

PHP and MySQL select

Okay so I'm making php that will pull every entry from a data base that matches the name you put in a textbox. so here is a image of the database
http://i.stack.imgur.com/LvmrM.png < screen shot of database
So if i where to put "DigitalNuke" in the textbox and hit the submit button I want only the rows that have "DigitalNuke" as the value in the second column "referrer"
<form ACTION="" METHOD=post>
<div class="input-append">
<input class="span2" id="youruser" type="text" name="youruser" placeholder="Your Username">
<button class="btn btn-success" type="submit">Retrive</button>
</div>
</form>
<?php
require_once 'connect.php';
$name = isset($_POST['youruser']);
$conn= mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname)or die(mysqli_error());
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
$result = mysqli_query($conn, $query1)
or die('Error querying the database: ');
echo '<table class="table table-bordered">';
echo '<caption>Your Referred Members</caption>' . '<thead><tr><th>ID</th>' . '<th>Username</th>' . '<th>Brigade</th>' . '<th>Faction</th>' . '<th>Activity</th>' . '</tr></thead>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='success'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['brigade'] . "</td><td>" . $row['faction'] . "</td><td>" . $row['activity'] ."</td></tr>";
}
?>
So as of now it doesn't do anything when I hit the submit button. Well it kind of works, except for instead of pulling the data from the table, it just puts id, username, brigade, faction, activity in each row of the generated table.
http://i.stack.imgur.com/XF71h.png < screen shot
Any help would be appreciated, if you need anything else let me know and i'll post it.
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
should be:
$query1 = "SELECT `id`, `referrer`, `username`, `brigade`, `faction`, `activity` FROM refmems WHERE referrer='$name'";
Also learn how to use prepared statements for MySQLi. Your code is open to SQL injection.
Your syntax is broken.
"SELECT id, referrer, username, brigade, faction, activity FROM refmems WHERE referrer='$name"
There is no closing single quote after $name, and the fields don't get quoted (or use backticks but it isn't necessary).
Also, you are asking for trouble. You've got user input with no validation/sanitization.

php + mysql comment system

I'm pretty new to php, and for that matter server scripting in general (so go easy on me)
But regardless of that I managed to create this, the first half of a comment system:
<html>
<body>
<form name="Comment" action="InsertComment.php" method="POST">
Name: <input type="text" name="name" /><br>
Comment: <br><textarea style="height: 100px; width: 600px;" name="comment"></textarea><br>
<input id="Special_ID" name="id" value="<?php $unixtime = time(); echo $unixtime; ?>">
<!--^Gathers a unique id^-->
<input type="submit" />
</form>
</body>
</html>
Once submitted -->
<?php
$con = mysql_connect("Blaa", "Blaa", "Blaa");
if(!$con) {
die('Could not connect ' . mysql_error());
}
sql_select_db("Comments", $con);
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('$_POST[name]', '$_POST[comment]', '$_POST[id]')";
?>
This is exactly what I wanted, a user puts in their name, a comment, and a unique post id (time stamp) is generated, then it is all sent to mysql.
But now I'm dumb found as to how I can post this to another page..
I assumed something like:
if(ID == [the id of that post]) {
//$_GET the mysql stuff
//Post inside a specially made div or something
}
Along the lines of that, but I have no clue how to put that into practise :/
Any ideas?
Oh and Please don't suggest an echo type post, I've done that and it's not at all what I want.
**Also this is just the basic code, I don't need suggestions on how to touch it up just yet, also errors in this is only due to my sleep deprivation, the code does work.
As #Marc B has said, you'll first want to fix your SQL injection holes using mysql_real_escape_string. Change your insert statement to
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('" . mysql_real_escape_string($_POST['name']) . "', '" . mysql_real_escape_string($_POST['comment']) . "', '" . mysql_real_escape_string($_POST['id']) . "')";
To display your comment, try this
$sql = "SELECT Name, Comment, ID
FROM Posts
WHERE ID = '" . mysql_real_escape_string($_GET['PostID']) . "'";
$query = mysql_query($sql);
echo "<div id=\"comments_container\">";
while ($row = mysql_fetch_assoc($query))
{
echo "<div class=\"comment\">";
echo "<div class=\"name\">" . $row['Name'] . "</div>";
echo "<div class=\"comment_body\">" . $row['Comment'] . "</div>";
echo "</div>"
}
echo "</div>";
Then CSS style your DIVs using IDs and classes.
Just an example using mysql_fetch_object
Please sanitize your $_GET data before inserting to MySQL, this is a huge injection security flaw.
$sql = "SELECT * FROM Posts WHERE id={$id}"
$result = mysql_query($sql);
$obj = mysql_fetch_object($result)
if(is_object($obj))
{
echo "Welcome " . $obj->Name;
}
A full length example is given here:
http://manzur-ashraf.com/code/auto_commenting_system/Automatic_Commenting_System_and_Email_notification_using_PHP_and_MYSQL.htm
In addition to using a MYSQL database to store the comments, you can also post email to the admin about new comments.

Combine $_GET and $_POST in PHP?

for some friends and family (different sites), I created a script that allows them to input data into the database. With
echo ("<a href=\"./pagina.php?ID=" . $row['ID'] . "\">" . $row['ID'] . "<br>");
, I 'send' the ID of the requested table to the URL.
In pagina.php, I have this code:
ID: <?php echo $_GET["ID"]; ?>
That works, of course, but now I want to use that ID to also display the data from the database, so not from the URL. These values are " . $row['onderwerp'] . " and " . $row['tekst'] . "
(There may be more values to come, but I'm just a beginner, trying to get something to work).
I know this is possible, but I just can't get anything to work, as I have just started learning PHP.
I hope you can help me.
If you don't care whether data came from a $_COOKIE, $_GET, or $_POST, you can use $_REQUEST.
$id = (int)$_GET['id'];
$sql = "SELECT onderwerp, tekst FROM yourtable WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo "{$row['onderwerp']} - {$row['tekst']}<br />";
}

Categories