PHP SQL Returning only one result - php

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>";
}

Related

Displaying Image From URL Stored in SQL Databse Using PHP

I'm trying to display images from a SQL Database (using an URL in the DB) in a table.
I'm still pretty new to this type of implementation so I've been giving it my best shot and trying to do research but haven't found much on using URLs (opposed to using BLOBs or directly adding images to the Database). I definitely WANT to keep my images on a file system. Currently my code only displays the URL (obviously) but I have tried a few things..
I have tried:
-Passing $row["card_image"] to a PHP variable $image and using $image->load()
-Using "<img src="$row["card_image"]">" (I imagined since I was getting a link output still this could work...)
-I have also tried a few other solutions that I've found on Stack Overflow but I believe these have mostly been for use with BLOB data types and so they also failed to produce the output I desire (I.E.
"<img src="data:image/jpeg;base64,'.base64_encode($image->load())'" />"
Here is my current code:
SQL (I have condensed the fields to save space)
CREATE TABLE cards (
card_image VARCHAR(999)
);
insert into cards (card_image)
values ('http://localhost/dbztc/wp-content/uploads/2016/04/1.jpg');
PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
if(!$conn)
{
die("connection failed");
}
//Table
echo "
<table cellpadding=\"0\" cellspacing=\"2\" border=\"0\" width=\"100%\">
<tr bgcolor=\"#666666\">
<td colspan=\"5\" align=\"center\"><b><font color=\"#FFFFFF\">" . $table[0] . "</font></td>
</tr>
<tr>
<td>Image</td>
<td>Card Number</td>
<td>Card Rarity</td>
<td>Card Name</td>
<td>Card Type</td>
<td>Card Style</td>
<td>Card Text</td>
</tr>";
$sqlquery = "SELECT card_image, card_number, card_rarity, card_title, card_type, card_style, card_text FROM cards";
$result = mysqli_query($conn, $sqlquery);
//$image = $row["card_image"];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . $row["card_image"] . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
}
} else {
echo "0 results";
}
echo "</table>";
mysqli_close($conn);
Instead of:
<td>" . $row["card_image"] . "</td>
Try:
$image = $row["card_image"]; // the image url
<td><img src='". $image . "'></td>
For anyone who stumbles upon this and may be having this same problem:
For starters, I took the entire URL out of the database entry and replaced it with the Filename only.
Afterwards, I edited my code like this:
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . "<img src ='../images/" . $row["card_image"] . "'>" . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
echo "<br />";
It now displays perfectly. Just as a note, this was done on a live server opposed to local so that could maybe also have an impact? Not sure, but hopefully this can help someone!

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);
?>

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'))";

Filtering mysql results via select dropdown

I'm a new member of StackOverflow, and although I've been using the website for a long time, it's my first time posting a question, in a hope that someone will be able to help me. I'll start by saying that my knowledge of PHP and MySQL is basic, but what I'm trying to do isn't too complex in my opinion, so hopefully I won't be asking for much. I've done a lot of prior research, but I just couldn't find the right answer.
In short, this is what I'm trying to do:
I've got an html form, which upon submission writes data to a database, and then publishes a table on a separate html page. With each successful submission a new table gets generated and published, while the old one gets pushed underneath. This all works fine, and I've also implemented pagination so that only 5 tables are visible per page.
What I'd like to be able to do is allow people to ONLY view/display results (tables) based on a specific criteria, in this case "rating", by selecting a rating from a drop-down on the page where tables are published. Rating is one of the fields in my form which gets submitted to a database and then published in one of the rows in a table.
Below is the code which publishes tables. Thanks in advance for your help!
<?php
include('dbconnect.php');
mysql_select_db("vtracker", $con);
$result = mysql_query("SELECT * FROM userdata");
$age = "Age:";
$rating = "Rating:";
$country = "From:";
$name = "Name:";
while($row = mysql_fetch_array($result))
{
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
?>
for both true and false use can add thid in your code:
if($_POST['rating_dropdown']!='')
{
$temp_rating = $_POST['rating_dropdown'];
$query=mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
}
else
{
$query=mysql_query("SELECT * FROM userdata");
}
Dunno if this works, it's just a hinch. haha.
It will see if the rating is true(not null), if it's true it will echo the results.
while($row = mysql_fetch_array($result))
{
if ($rating)
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
}
Once the dropdown gets selected and posted to your display page, use this code:
$temp_rating = $_POST['rating_dropdown'];
mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
Keep in mind, however, that you should be using PDO or mysqli extension, not the mysql extension. According to PHP's website:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.

Using PHP forms in mysql queries

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.

Categories