Using PHP forms in mysql queries - php

Another (basic) question here. I need to know how to use html forms to filter the results of a mysql query using PHP. I have been looking at w3schools and I can see how using $_POST on one page can output to another page. But I cannot see exactly how to put the $_POST into my query. For example I have one page as below:
<form action="orderlist.php" method="post">
OrderNo: <input type="int" name="order_no" />
<input type="Submit" />
</form>
This is a page where the user can enter an order_no and click submit, which links to the 'orderslist.php' page. On that page I have the following code:
$result = mysql_query("SELECT * FROM orders");
echo "<table border='5'>
<tr>
<th>order_no</th>
<th>ord_date</th>
<th>est_completion_date</th>
<th>status</th>
<th>invoice_date</th>
<th>inv_amount</th>
<th>name</th>
<th>fName</th>
<th>lName</th>
</tr>";
// -- Use 'while' to check each row in $result in turn:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['order_no'] . "</td>";
echo "<td>" . $row['ord_date'] . "</td>";
echo "<td>" . $row['est_completion_date'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['invoice_date'] . "</td>";
echo "<td>" . $row['inv_amount'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fName'] . "</td>";
echo "<td>" . $row['lName'] . "</td>";
echo "</tr>";
}
echo "</table>";
This outputs everything from 'orders' into a table, but I want it to only output the row with the order_no that the user entered on the previous page. How do I do this? Is it something like:
$result = mysql_query("SELECT * FROM orders WHERE order_no = $_POST[order_no]");
Thank a lot

For starters, you should switch to PDO or mysqli -- the mysql_* functions are in the process of deprecation.
On to your question: yes, that's how you do it, with a WHERE clause. However, it is very (very very very) insecure to concatenate a variable directly out of $_POST without sanitation.
That said, at a minimum you should do this:
mysql_query('SELECT * FROM orders WHERE order_no = '.mysql_real_escape_string($_POST[order_no]));
Another thing... don't use SELECT *. You should always list the columns you expect to get from the database -- that way, if there is a problem (like the columns have changed), the query can let you know. With SELECT * you get back a magical grab-bag of data -- you have no idea what it is, and more importantly, if it has the values your code relies on.
So, putting it together:
$pdo = new PDO("mysql:host=localhost;dbname=database", '-username-', '-password-');
$sth = $pdo->prepare('
SELECT
`order_no`,
`ord_date`,
`est_completion_date`,
`status`,
`invoice_date`,
`inv_amount`,
`name`,
`fName`,
`lName`
FROM
orders
WHERE
order_no = :order_no
');
$sth->execute(array(':order_no'=>$_POST[order_no]));
while ($order= $sth->fetch()) {
echo "<tr>";
echo "<td>" . $order->order_no . "</td>";
echo "<td>" . $order->ord_date . "</td>";
echo "<td>" . $order->est_completion_date . "</td>";
echo "<td>" . $order->status . "</td>";
echo "<td>" . $order->invoice_date . "</td>";
echo "<td>" . $order->inv_amount . "</td>";
echo "<td>" . $order->name . "</td>";
echo "<td>" . $order->fName . "</td>";
echo "<td>" . $order->lName . "</td>";
echo "</tr>";
}
Edit: One last note, the input you're using is not valid; type="int" is not a recognized input type. Here's a list of types for HTML 4, and a list for HTML 5:
As you can see, HTML 5 does have a new input type "number". It is not fully adopted, but if you wanted to use it:
<input type="number" name="order_no" />
Be aware, however, that not all browsers will restrict the input to numeric: http://caniuse.com/#feat=input-number
Documentation
mySql SELECT - http://dev.mysql.com/doc/refman/5.0/en/select.html
mysql_query (DEPRECATED) - http://php.net/manual/en/function.mysql-query.php
PDO - http://www.php.net/manual/en/book.pdo.php
PDO::prepare - http://www.php.net/manual/en/pdo.prepare.php
PDOStatement::fetch - http://www.php.net/manual/en/pdostatement.fetch.php
PDOStatement::execute - http://www.php.net/manual/en/pdostatement.execute.php

Without injection vulnerability (require 'mysql_connect' before) :
if(isset($_POST['order_no']))
{
$orderNo = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNo");
echo "<table border='5'>";
echo " <tr>";
echo " <th>order_no</th>";
echo " <th>ord_date</th>";
echo " <th>est_completion_date</th>";
echo " <th>status</th>";
echo " <th>invoice_date</th>";
echo " <th>inv_amount</th>";
echo " <th>name</th>";
echo " <th>fName</th>";
echo " <th>lName</th>";
echo " </tr>";
if(mysql_num_rows($result) == 0)
{
echo '<tr><td colspan="9">Order not found</td></tr>';
}
else
{
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo " <td>" . $row['order_no'] . "</td>";
echo " <td>" . $row['ord_date'] . "</td>";
echo " <td>" . $row['est_completion_date'] . "</td>";
echo " <td>" . $row['status'] . "</td>";
echo " <td>" . $row['invoice_date'] . "</td>";
echo " <td>" . $row['inv_amount'] . "</td>";
echo " <td>" . $row['name'] . "</td>";
echo " <td>" . $row['fName'] . "</td>";
echo " <td>" . $row['lName'] . "</td>";
echo "</tr>";
}
}
echo "</table>";
}

Try this:
$orderNumber = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNumber");
This takes the value of $_POST['order_no'] and somewhat sanitizes it. You then apply the value of $orderNumber to MySQL.
However, you're much better off using PDO or MySQLi. Both protect you (if used correctly) from SQL injection. Currenly, your code is VERY prone to SQL injection.

Your form should be something like this:
<form action="orderlist.php" method="post">
OrderNo: <input type="text" name="order_no" />
<input type="Submit" value="Submit"/>
</form>
To get any value that is typed by user in the form you should use type="text".
There is nothing like type="int" in standard HTML.
Don't get confused, the Input TYPE in HTML is not the same as one you use in Programming languages to declare Data type. Here TYPE is just to let the browser know that its a text field / Radio Button etc.
To understand Valid Input Types better read this w3.org recommendation on HTML forms.
On orderlist.php you can query to retrieve the required data:
if(isset($_POST['order_no'])) {
$orderNo = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNo");
while($row = mysql_fetch_array($result)) {
//code to print table.
}
}
Note:
This type of code is Vulnerable to easy attacks, and it is never recommended to put user input directly into SQL query, it should always be filtered first.

Related

PHP SQL Returning only one result

Im trying to migrate my website from my local wamp project to my live server for testing, everything is working fine on my local site but on my live site the following code only returns one result. There are definitely multiple SQL entries that meet the sql query criteria. Any suggestions?
$opentickets = $db->query("SELECT tID, id, date, userid, category, department FROM ticket WHERE userid = '$_SESSION[id]' AND status='Open'");
if(count($opentickets) > 0) {
echo "<h2>Your open tickets:</h2>";
echo "<table class='table table-striped'>
<tr>
<th>Ticket</th>
<th>Date Submitted</th>
<th>Category</th>
<th>Department</th></tr>";
$o = $opentickets->fetch(PDO::FETCH_ASSOC);
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" . $o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
echo "</table>";
}
else
{
echo "<h2>You have no open tickets</h2>";
}
You are not itterating over the results of your query, you are just fetching the first row...
Please reference to the examples on the PHP Website on how to do this.
I have just changed your code below, please check for the manuals for more information
while($o = $opentickets->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" .$o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
}

I need a table cell to be a form to input specific data to mysql?

I have no idea how to explain myself which is why the question isn't even a question. I need to have a table dynamically created from data on mysql (which I've done) but I need to be able to have input in the cells under some of the headings (responsibility, organization, independent work...) When this data is submitted, I need it to be student specific. In other words, when I pull up Johnny Rotten's data, I need to be able to see all the comments under those headings that were submitted (yes this is for teaching). The number of students can vary which is why i need the whole thing to be dynamic. If this is not possible, please let me know. AND if you haven't figured it out already, I am brand new and self-taught!
Here's what I have...
<?php
include 'connect.php';
if ($db_found) {
$SQL = "SELECT * FROM studentlist WHERE teacher1='smith' OR teacher2 ='smith' OR
teacher3='smith' ORDER by homeroom";
$result = mysql_query($SQL);
echo "<table border='1'>
<tr>
<th>Student</th>
<th>Homeroom</th>
<th>Responsibility</th>
<th>Organization</th>
<th>Independent Work</th>
<th>Collaboration</th>
<th>Initiative</th>
<th>Self Regulation</th>
</tr>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['student'] . "</td>";
echo "<td>" . $row['homeroom'] . "</td>";
echo "<td>" . "" . "</td>";
echo "<td>" . "" . "</td>";
echo "<td>" . "" . "</td>";
echo "<td>" . "" . "</td>";
echo "<td>" . "" . "</td>";
echo "<td>" . "" . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($connect);
?>

Select 2 tables in one php select statement

I have two tables in mysql
practice_sheets and parent_pin
And I want to use one select statement and get data from both tables.
I have tried
$result = mysqli_query($con,"SELECT * FROM practice_sheets AND parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
and also:
$result = mysqli_query($con,"SELECT * FROM practice_sheets, parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
I've never tried to do this before and the previous solutions are what I found searching.
Update
I think it would help if I included my full code. the table data is going into a table on my page. the student_name field from the practice_sheets and parents_student from parent_pin will be matched.
<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM practice_sheets
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
$numrows = mysqli_num_rows($result);
if($numrows == 0) {
echo "<div class='alert alert-danger'>";
echo "No Entries, See your instructor for details.";
echo "</div>";
} else {
echo "<table class='mws-table table-striped table-hover'>";
echo "<thead align='center'>";
echo "<tr>";
echo "<th>Sheet Number</th>";
echo "<th>Total Minutes</th>";
echo "<th>Due Date</th>";
echo "<th>PIN</th>";
echo "<th>View</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody align='center'>";
while($row = mysqli_fetch_array($result)){
if ($row["total_min"]>=$row["required_min"]) {
echo "<tr class='success'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
} else {
echo "<tr class='info'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
$result = mysqli_query($con,"SELECT *
FROM practice_sheets, parent_pin
WHERE student_name = parents_student
AND student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
Use explicit names for WHERE statament, e.g.
$result = mysqli_query("SELECT student_name.practice_sheets FROM practice_sheets AND parent_pin WHERE student_name.practice_sheets = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
MySQL will not AFAIK automatically check where the constraints are and rightly so considering that you may have conflicting names. Note that this is still pseudo code and you will need to change the fetched results accordingly. Usually it is considered to be good practice to also define explicitly the columns you wish to fetch, but otherwise you can use JOIN as well.
And to help writing shorter code, you can also use shorthands for the table names, e.g.
$result = mysqli_query("SELECT student_name.ps AS name, pin.pp AS pin FROM practice_sheets AS ps, parent_pin AS pp WHERE student_name.ps = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
Update
You also have in your updated version an issue. You call mysqli_fetch_array, which returns an ordered (i.e. numbered) array. If you wish to use keyed, use mysqli_fetch_assoc.
And you are closing the MySQL connection at the moment only if the query was successful. Move mysqli_close outside of the brackets.

Use Buttons In Table - PHP

I'm following through a tutorial from a book I have but want to add some extra columns to a table. I have added the columns, buy and sell, and in each of those I want to display a button. I am unsure of how to do this, is it possible?
Here's my code from the page with the table:
<?php // Example 21-9: members.php
include_once 'header.php';
if (!$loggedin) die();
echo "<div class='main'>";
$con=mysqli_connect("localhost","root","usbw","stocktrading");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM stocks");
echo "<table border='1 '>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Buy</th>
<th>Sell</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td><input type='radio' name='buysell' value='buy'></td>";
echo "<td><input type='radio' name='buysell' value='sell'></td>";
echo "</tr>";
Something like this will add radio buttons. Use checkboxes or another kind of button if you prefer.
I know that you must be a new programmer, but there's some cool things that you can use for avoid string concatenation. String concatenation sometimes can make your code messy and unreadable, and it's not cool.
You can use HEREDOC for avoid concatenation(please, avoid concatenation). Also, when using HEREDOC or double quotes " you can use {} to access array keys or object attributes.
i.e with HEREDOC:
// Guys, look, it's a HEREDOC, it make the HTML more readable :)
$html = <<<EOF
<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
<td><button>Sell</button><td>
<td><button>Buy</button><td>
</tr>
EOF;
i.e with double quotes ":
$html = "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
<td><button>Sell</button><td>
<td><button>Buy</button><td>
</tr>";
But, if i need to call some functions?
sprintf or printf can be the solution
spritnf: returns a string produced according to the formatting string format.
printf: prints a string produced according to the formatting string format.
i.e:
$str = sprintf("My name is <b>%s</b>", ucfirst("i am not procrastinating"));
echo $str;
//OR
printf("My name is <b>%s</b>", ucfirst("i am not procrastinating"));
Or using an template way(may be hard) using str_replace, array_keys and array_values.
$template = "My name is <b>:name:</b>, i'm from :from:.";
$templateVars = array(
":name:" => "I am not procrastinating",
":from:" => "Brazil"
);
echo str_replace(array_keys($templateVars),array_values($templateVars),$template);
Happy Coding.
Sorry for the English, but i'm Brazilian, and we don't speak English, not even Spanish haha.
just add the button inside the td
echo "<tr>".
"<td>" . $row['id'] . "</td>" .
"<td>" . $row['name'] . "</td>" .
"<td>" . $row['price'] . "</td>" .
'<td><button>Sell</button><td>' .
'<td><button>Buy</button><td>' .
"</tr>";

SQL removing data from an array depending on field value

I'm still quite new to this and have come across a problem I have been looking through a lot of tutorials and cannot figure a way to get over the problem.
I have a select query getting data out of my sql database however I need the data to be custom for each user who accesses it, so need to add a further query, I have a cookie read in with the user value '$user' and there is a collumn in the database that isnt put into the table however need to check that if the collumn 'privacy' has a value set as '1' and the $user is not the investigator of that row discard and do not put into the table. however populate with all data that isn't set to privacy='1' or is set to privacy=1 and the investigator='$user'
$sql="SELECT * FROM evidence WHERE $evidencevariable = '".$evidencespecify."'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());}
echo "<table class='sortable' border='1' id='table'>
<thead><tr>
<th>Id</th>
<th>Case Id</th>
<th>Investigator</th>
<th>Evidence Type</th>
<th>Created</th>
<th>Modified</th>
<th>LS</th>
<th>PS</th>
<th>Length</th>
<th>Importance</th>
<th>Information</th>
</tr></thead><tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Id'] . "</td>";
echo "<td>" . $row['Case_ID'] . "</td>";
echo "<td>" . $row['Investigator'] . "</td>";
echo "<td>" . $row['Evidence_Type'] . "</td>";
echo "<td>" . $row['Created'] . "</td>";
echo "<td>" . $row['Modified'] . "</td>";
echo "<td>" . $row['LS'] . "</td>";
echo "<td>" . $row['PS'] . "</td>";
echo "<td>" . $row['Length'] . "</td>";
echo "<td>" . $row['Importance'] . "</td>";
echo "<td>" . $row['Information'] . "</td>";
echo "</tr>";
}
echo "</tbody></table>";
How can I get around this problem do I need to add more to the select statement at the beginning or is there a way of querying the array to remove the data before its put into the table?
Any help would be appreciated!
It seems you can easily modify the sql to something like:
$sql="SELECT * FROM user WHERE $evidencevariable='$evidencespecifiy' AND (Privacy=0 or (Privacy=1 AND investigator='$user'))";

Categories