php return multiple variables from other page - php

I'm trying to create a table with links that return a 'mf_id' value and its corresponding 'Manufacturer' value. I can do one at a time, but when I try to combine the two, problems begin to crop up. Here's what I have so far:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Manufacturer'] . "</td>";
echo "</tr>";
}
and the other page:
$numb = $_GET['mf_id'];
$name = $_GET['Manufacturer'];
echo "<h1>$name</h1>";
$result=mysql_query("select * from Products where mf_id=$numb");
Thanks in advance!

Because you never pass Manufacturer through your querystring, the second page doesn't have access to it via GET. Also, for validity purposes, your querystring values should be passed through urlencode().
This line:
echo "<td>" . $row['Manufacturer'] . "</td>";
Should be:
echo "<td>" . $row['Manufacturer'] . "</td>";
Please Note: It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
UPDATE:
Per meagar's advice I learned about http_build_query(). This is definitely the way to go when writing querystrings to URLs:
$data = array('mf_id' => $row['mf_id'], 'Manufacturer' => $row['Manufacturer']);
echo "<td><a href='list.php?" . http_build_query($data) . "'>" . $row['Manufacturer'] . "</a></td>";

This doesn't make any sense at all: $row['mf_id'&&'Manufacturer']. That is not how you access two elements of an array. You're combining two strings with &&, yielding boolean true, and attempting to access $row[true]. You can't access an array that way.
If you want to use both items, you need to access them individually:
$row['mf_id'] . $row['Manufacturer']
If you want to build a query string containing these two values, you should use http_build_query which will take care of URL-encoding your data:
$query = http_build_query(array('mf_id' => $row['mf_id'], 'manufacturer' => $row['Manufacturer']));
echo '<td>' . $row['Manufacturer'] . '</td>';
Note that, if you actually just select the fields you need, you don't have to explicitly specify them in the arguments to http_build_query. If your $row already contains only mf_id and manufacturer, it would be enough to use
$query = http_build_query($row);

You're only passing mf_id into the page, you are not passing Manufacturer.
Edit (as you've changed your code)
Change:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Manufacturer'] . "</td>";
echo "</tr>";
}
To:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Manufacturer'] . "</td>";
echo "</tr>";
}

Related

PHP displays only one word from MySQL record in URL variable

A PHP page displays only one word from a MySQL record in a URL variable, while it displays the correct 2 words in the HTML output, I tried many solutions such '".$row['book_category']."' and {$row['book_category']} etc. but I still get the same one result.
<?php
foreach($conn->query('SELECT book_category, COUNT(*) FROM books GROUP BY book_category') as $row) {
echo "<tr>";
echo "<td>" . "" . $row['book_category'] . "" . "</td>";
echo "</tr>";
}
?>
So now first $row insert is only one word in the url, while the second $row outputs two words properly as expected; the problem is I need the two words to be passed as variable in the URL.
URLs cannot have a space character, this is why you are seeing the first word only, you need to encode the value received using rawurlencode().
<?php
foreach($conn->query('SELECT book_category, COUNT(*) FROM books GROUP BY book_category') as $row) {
echo "<tr>";
echo "<td>" . "<a href='sidebar_cat_display.php?book_cat=" . rawurlencode($row['book_category']) . "'>" . $row['book_category'] . "</a>" . "</td>";
echo "</tr>";
}
?>
Keep in mind you will also need to adjust the sidebar_cat_display.php page to fetch the book_cat parameter from the URL accordingly if you aren't already.

PHP array initialized inside if($_POST) block can't be used outside of it

I have been looking all over to find out why this is happening, but to no avail. I have a 2-step process to update specific rows (to approve timesheets) in a mySQL database based off what checkboxes are checked. In the first screen, the user checks whichever checkboxes associated with the timesheet she or he wants to update. On the next screen, I display the rows associated with those checkboxes, a confirmation page - if you will. On this confirmation page, I successfully set and echo out an array that is simply a copy of the $_POST checkbox array, called 'approvebox'. Despite this, I seemingly cannot use this array anywhere outside of the "if($_POST)" block that it is created in.
Here is the code associated with creating the first page, where the user must check the checkboxes for each timesheet she/he wishes to approve:
if($_POST['submit']){
...
...
while ($row = mysqli_fetch_assoc($tblresults)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['timesheetsid'] . "</td>";
echo "<td>" . $row['unixstamp'] . "</td>";
echo "<td>" . $row['total_hours'] . "</td>";
echo "<td>" . $row['coordinatorid'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>(<a href='./currenttimesheets.php?timesheetsid=" . $row['timesheetsid'] . "'>View</a>)</td>";
echo "<td> &nbsp &nbsp &nbsp <input type='checkbox' name='approvebox[{$row['timesheetsid']}]' value='{$row['timesheetsid']}' /></td>";
echo "</tr>";
}
Here is the code in which I successfully set and echo the array that is a copy of the $_POST approvebox array. Also worth noting that I actually use the approvebox array from the if($_POST['submit']) block in a foreach loop to populate the resulting rows the user selected from the prior screen:
if($_POST['appove']){
...
...
foreach ($_POST['approvebox'] as $approvebox){
...
...
while($row = mysqli_fetch_assoc($tblresults)){
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['timesheetsid'] . "</td>";
echo "<td>" . $row['unixstamp'] . "</td>";
echo "<td>" . $row['total_hours'] . "</td>";
echo "<td>" . $row['coordinatorid'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>(<a href='./currenttimesheets.php?timesheetsid=" . $row['timesheetsid'] . "'>View</a>)</td>";
echo "</tr>";
}
}
echo "</table>";
print_r($_POST);
$selectedtimesheets = array();
$selectedtimesheets2 = array_merge($selectedtimesheets, $_POST['approvebox']);
//$selectedtimesheets2 is successfully set to the $_POST array here
print_r($selectedtimesheets2);
Finally, here is the second if($_POST) block, in which I try to use the $selectedtimesheets2 array in, but to no success, it doesn't echo out anything:
if($_POST['accept']){
print_r($_POST);
//$selectedtimesheets2 does not get echoed out, despite being successfully set and echoed previously..
print_r($selectedtimesheets2);
echo $selectedtimesheets2;
It sounds like you are doing two requests. Whatever was in the superglobal _POST after the first request won't be in the next request.
To preserve data between requests, you can use PHP sessions.
You could do something like this: on first request, save that array into the session:
session_start();
$_SESSION["selectedtimesheets2"] = array_merge($selectedtimesheets,
$_POST['approvebox']);
Then in your next request, you can retrieve it:
$selectedtimesheets2 = $_SESSION["selectedtimesheets2"]
Does that make sense? This is very crude, I would suggest maybe using a framework like Symfony, Laravel or Lumen, depending on size of your project. HTTP requests have been abstracted and are much easier/safer to manipulate. Also have a look at the HTTP foundation package from Symfony.
shouldn't print_r($_POST); be print_r($_POST['approve']);

How to put user input into a SQL Query

I have a database and I want the user to be able to have an input into what comes out. i.e
Select from Table where example = user input from box **(input by the user)**
Im guessing what I need is a variable to hold the value that then goes into the statement. I know how to get the value from the input box with script but can I use it like:
select * From handover WHERE hdate = variable. However I am guessing someone is going to talk to me about security if its even possible.
<html><body>
<input>User input</input> //That needs to go into statement
<?php
include 'config.php';
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = **user input**;");
echo "<table border='1'>
<tr>
<th>hdate</th>
<th>Delay</th>
<th>Health and Safety</th>
<th>Non Vsa</th>
<th>VSA</th>
<th>Dar</th>
<th>Other</th>
<th>Hour</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['hdate'] . "</td>";
echo "<td>" . $row['hdelay'] . "</td>";
echo "<td>" . $row['hs'] . "</td>";
echo "<td>" . $row['nv'] . "</td>";
echo "<td>" . $row['vsa'] . "</td>";
echo "<td>" . $row['dar'] . "</td>";
echo "<td>" . $row['other'] . "</td>";
echo "<td>" . $row['hour'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Any help is welcome and advice on the best language to use for this.
Kind Regards
Fintan
first of all, this question has nothing to do with javascript & ajax. so you can delete those tags.
you want to show/search data from mysql.
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = '".$_POST['abc']."' ");
this is when you want to check if hdate column have exact data as user input ( $_POST['abc'] ).
and also don't forget to use mysqli_real_escape_string
you can learn common mysql pattern queries from here: http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html

How can I access query results in php where I'm returning values AS things? (Rather than looking at fields)

Apologies, I can't think of how to phrase this better (which has the additional problem of making it more difficult to research an answer, too). Suggestions for editing terms for clarity are more than welcome.
I am running two queries on a table in my database. The first simply returns all results within certain constraints imposed by the user - I'm echoing this out to a table with no problems at all. The second returns a COUNT and a SUM AS things, which I am having trouble accessing and echoing to the screen.
First Query -
$results = $connection->query(" SELECT `Date`, `Test`, `Errors` ... ");
while($result = $results->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $result['Date'] . "</td>";
echo "<td>" . $result['Test'] . "</td>";
echo "<td>" . $result['Errors'] . "</td>";
echo "</tr>";
}
This works perfectly well. As expected, it echos out a table with the results in each row.
Second Query -
$totals = $connection-query("SELECT COUNT(*) AS Tests, SUM(`Errors`) AS TotalErrors ... ");
echo "<th>Total Tests</th>";
echo "<td>" . $totals['Tests'] . "</td>";
echo "<th>Total Errors</th>";
echo "<td>" . $totals['TotalErrors'] . "</td>";
I cannot seem to access the values in the second query to echo them to the screen.
I have tried using var_dump to ensure the query is returning results correctly, and it is. If I use var_dump($totals->fetch_assoc()); it will display array(2) { ["Tests"]=> string(2) "33" ["TotalErrors"]=> string(1) "9" }, as expected.
I'm not sure where I'm going wrong, looking at my syntax, it seems the same as when I access the values from the first query, but I'm not sure if it should be different because I am returning values AS rather than looking at field names.
Try
$results = $connection->query("SELECT COUNT(*) AS Tests, SUM(`Errors`) AS TotalErrors ... ");
$totals = $results->fetch_assoc();
echo "<th>Total Tests</th>;
echo "<td>" . $totals['Tests'] . "</td>";
echo "<th>Total Errors</th>";
echo "<td>" . $totals['TotalErrors'] . "</td>";

Sending MySQL data to page through link in a table

We are currently working on a game shop website and have hit a roadblock regarding the purchase link.
The link displays within a mysql table and each link sends the user to the same page.
This is necessary as we will be adding new games to the database and want to do using only a mysql command to make the site as efficient as possible.
This is the code of the table (ignore the fact that the purchase link displays the 'gameCodes'.
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['gameName'] . "</td>";
echo "<td>" . $row['pointsValue'] . "</td>";
echo "<td>" . ''. $row['gameCodes'] .'' . "</td>";
echo "</tr>";
}
echo "</table>";
What I am wanting to do is send the game code of the game that corresponds with the row the link is on to the Purchase.php page to then process the purchase.
Any help is appreciated greatly.
my answer deals with not only passing variables from url to your page....but passing it in clean way
First, make sure that url URL properly encode using "PHP urlencode"
echo "<td>" .
'<a href="Purchase.php?gameCodes='.urlencode($row['gameCodes']) .'">'.
$row['gameCodes'] .
'</a>' .
"</td>";
Then to fetch the data strip_tags from the url variable if any:
echo (strip_tags($_GET['item']));
why is this needed??
Since you are fetching the values from URL, assume i manually change the url to :
Purchase.php?gameCodes=<script>alert("hello")</script>
then without proper handling, gameCodes variable value will be fetched and it would alert "hello" on the page
Have you thought about sending it through the URL like follow:
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['gameName'] . "</td>";
echo "<td>" . $row['pointsValue'] . "</td>";
echo "<td>" . ''. $row['gameCodes'] .'' . "</td>";
echo "</tr>";
}
echo "</table>";
and then process to the purchase using the code sent in the URL
let me know if it corresponds to what you need.
I think you can put the gameCodes id directly in the link
echo "<td>" .
'<a href="Purchase.php?gameCodes='. $row['gameCodes'] .'">'.
$row['gameCodes'] .
'</a>' .
"</td>";
Now you can process the code from the purchase page and retrieve it with $_GET
$_GET['gameCodes'];

Categories