I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.
Related
This question already exists:
PHP's white screen of death [duplicate]
Closed 6 years ago.
I am currently in a class at school and we have to link our MySQL database with our website using php. I already made and populated my tables in MySQL. My professor sent us this chunk of code to display the table info on our websites. However when I run it nothing happens and I haven't learned enough about php to know why it is not working. I used my correct host name, password, ect. But it won't work and when he does the tutorial online in the video it works for him.
This is the code I am using.
<html>
<head>
<title>Query All Movies from Database</title>
<body>
<?
# $db = mysql_pconnect("localhost","username","password");
if (!$db)
{
echo "ERROR: Could not connect to database. Please try again later.";
exit;
}
mysql_select_db("database name");
$query = "select * from movie";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
echo "<p>Number of movies found: ".$num_results."</p>";
for ($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo "<p>";
echo htmlspecialchars( stripslashes($row["movieid"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["title"]));
echo "<br>";
//echo htmlspecialchars( stripslashes($row["directorid"]));
//echo "<br>";
echo htmlspecialchars( stripslashes($row["year"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["genre"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["runtime"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["plotdescription"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["comments"]));
echo "<br>";
echo "</p>";
}
?>
</body>
</html>
This is the output I am getting.
Directly to the screen.
Number of movies found: ".$num_results."
"; for ($i=0; $i < $num_results; $i++) { $row = mysql_fetch_array($result); echo "
"; echo htmlspecialchars( stripslashes($row["movieid"])); echo "
"; echo htmlspecialchars( stripslashes($row["title"])); echo "
"; //echo htmlspecialchars( stripslashes($row["directorid"])); //echo "
"; echo htmlspecialchars( stripslashes($row["year"])); echo "
"; echo htmlspecialchars( stripslashes($row["genre"])); echo "
"; echo htmlspecialchars( stripslashes($row["runtime"])); echo "
"; echo htmlspecialchars( stripslashes($row["plotdescription"])); echo "
"; echo htmlspecialchars( stripslashes($row["comments"])); echo "
"; echo "
"; } ?>
I did alot of research and read the links and here is the working code! Thanks for helping teach me!! This site is so great! You guys are awesome!
<?php
$servername = "localhost";
$username = "ursername";
$password = "password";
$dbname = "database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT movieid, title, directorid, year, genre, runtime, plotdescription, comments FROM movie";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Movie ID: " . $row["movieid"]. "<br>Title: " . $row["title"]. "<br>Director ID: " . $row["directorid"]. "<br>Year: " . $row["year"]. "<br>Genre: " . $row["genre"]. "<br>Run Time: " . $row["runtime"]. "<br>Plot Description: " . $row["plotdescription"]. "<br>Comments: " . $row["comments"]." <br><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Don't use that code - that snippet is not secure these days. You should be using one of the newer connection methods like PDO or MySQLI. I prefer the latter, try using the docs on PHP's site to set up your stuff.
http://php.net/manual/en/function.mysqli-connect.php
The only reason I could imagine that your teacher is using this method is either they don't know any better or they are using a very old version of PHP.
Older MySQL functions are procedural and get wonky when writing in OOP (object oriented programming) because they are manually escaped. The newer mysqli_ functions work with both procedural and OOP and support prepared statements. Prepared statements are safer because they parameterize the values so you run into less issues with SQL injection and other vulnerabilities. You also get some speed enhancements because the prepared statements only have to parsed on the preparation and not the execution. So if you use a lot of the same parameters you get some extra speed!
PDO also supports prepared statements, but its a little more complex for newcomers because it introduces an abstraction layer (basically you build the query in PHP instead of raw SQL statements). This was a turn off for me when I first started so I would try getting good at the MySQLi stuff before you look too deep into PDO.
There are so many fundamental issues here, but it seems like the issue with your output being wrong is because you're concenating the echo string, and doing wrong. With PHP you can put variables inside of double quotes and it will still parse correctly. And as I said, the code you have posted cannot be outputting that.
So change your first echo line to this and see what happens.
echo "<p>Number of movies found: $num_results</p>";
I always say, it's far better to teach yourself something than learn from a so called professor. He has given you depreciated code, that is now removed in PHP 7. He has told you i don't know what's wrong with your code and completely steered you in the wrong direction for secure, modern web development. This professor has no business teaching anyone PHP.
I'm trying to learn PHP, and to do so I'm attempting to create a URL shortener. Right now you can currently input a link and it enters it into the database. It doesn't randomize the string, but I'm going to do that after. (I changed them myself to avoid running into problems).
Here is my table currently(My table is called 'urls'):
Then when you go to (for me localhost) /somepath it automatically redirects to /process.php?id=somepath
In process.php it checks if the specified path (somepath) exists in the database, then gets its original value. The problem I'm having is getting the original value. Again, I am new to PHP, and I'm having trouble understanding how querying works.
$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
How do I grab information from $result? Or am I supposed to get it from $query after $result because that just basically runs it?
Please explain why you use what, I'm not understanding this.
Thanks, sorry if this is a really stupid question.
In this code, I used the object oriented approach for a prepared statement or if you are still into procedural style, you can still use that.
Check this link: http://php.net/manual/en/mysqli.prepare.php
So basically, what happens in this code is that the query is being prepared then you bind the parameter to be used (this style is one way to avoid SQL injections because inputs are automatically escaped). The result will be first stored in the variable $original then I counted how many rows the query returned. If it is more than 1, it means there is a match, then if 0, no match.
If there is a match, it will echo the value of the variable $original.
<?php
$stmt = $conn -> prepare("SELECT original FROM urls WHERE new = ?");
$stmt -> bind_param('s',$new);
$stmt -> execute();
$stmt -> bind_result($original);
$stmt -> fetch();
$stmt -> store_result();
$res = $stmt -> num_rows();
$stmt -> close();
if($res > 0){
echo $original;
}
else{
//not found
}
?>
Use fetch_assoc() to grab data from your table in MySQLi Object-oriented.
Try this:
$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
You can also put the result in an HTML table:
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
$rows = mysql_fetch_array($result);
foreach($rows as $row){
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
You can use either mysql_fetch_array or mysql_fetch_assoc for grab results
This is my script and it's displaying a blank, I have no idea what the problem is. HELP!!!! #new to PHP
<?php include "connection.php";
// Get the ID from URL.
if(isset($_GET['id']));
$id = $_GET['id'];
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query);
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
?>
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id= 'Careers'' at line 1
One obvious problem here is that you've included an "end of statement" character being a semi-colon.
The semi-colon (if that isn't a typo), is doing just that, "ending" the statement.
if(isset($_GET['id']));
^ right there.
It should be a brace { for it instead and to read as:
if(isset($_GET['id'])){
and there should be a closing brace } for that conditional statement for it.
Sidenote: The semi-colon is considered a valid character in PHP, which won't throw you an error for it, should the GET array have a value.
However, you should check for errors for the rest of your code.
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything,
as well as or die(mysqli_error($m)) to mysqli_query().
While making sure you are indeed using the MySQLi_ API to connect with (different MySQL APIs do not intermix) and that the GET array has a value.
Here's a rewrite, and assuming a successful DB connection using the MySQLi_ API for it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_GET['id'])){
$id = $_GET['id'];
} else{
echo "ID is not set. You need to investigate it.";
exit; // This will stop your script, dead in its tracks.
}
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query) or die(mysqli_error($m));
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.error.php
Edit:
Taken from comments:
"this is my query, $query="SELECT id, title module WHERE id= '$id'"; – user5579012 38 mins ago"
Link to that comment...
That isn't what was posted in your original question.
You posted SELECT * FROM module WHERE id= '$id'.
You have a syntax error here, being a missing comma after title.
It should read as:
$query="SELECT id, title, module WHERE id= '$id'";
All columns need to be seperated by commas but not the last one being module here.
Ensure everything is ok. Echo errors if possible.
<?php include "connection.php";
// Get the ID from URL.
if(isset($_GET['id'])){
$id = $_GET['id'];
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query);
if($result){ //query is ok
if(mysqli_num_rows($result) > 0){//check if a record exists
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
}else{ //no result found
echo "no results found!";
}
}else{ //some error in querying
echo mysqli_error($m);
}
}
?>
I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}
I am still a beginner with php and MySQL. I am having trouble getting rows from my database to display in an html select drop down box. I have researched it and it seems like my code should be good. The campaigns table as a row titled name. This is the row I am wanting to echo into the drop down. The drop down shows, however there is no content in it. Not sure what I am missing here...
Here is the code
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con,"SELECT * FROM campaigns");
echo '<select name="campaignChange">';
while ($row = mysql_fetch_array($query)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo '</select>';
?>
You are mixing mysql and mysqli syntax.
You should change:
$query = mysql_query($con,"SELECT * FROM campaigns");
to:
$query = mysqli_query($con,"SELECT * FROM campaigns");
and:
while ($row = mysql_fetch_array($query)) {
to:
while ($row = mysqli_fetch_array($query)) {
By the way, you should add error handling. If you add this to the top:
mysqli_report(MYSQLI_REPORT_ALL);
mysqli will throw exceptions so you will always know what goes wrong exactly. As long as you use mysqli functions of course...