Run a MySQL query trough pressing a link and escaping backslash - php

I have this PHP code below that prints the result of a MySQL query in a HTML table. Furthermore, in the table, I create a link of the result that will be used in another query. Lets take a look at the code:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
This code works as intended, but now comes the problem: I want to implement the following: Once you click on the link, another query should be executed, this one to be specific: SELECT * FROM fileDB WHERE filepath = 'the one sent from the link'. I thought to use something like $_GET["filepath"] from the link to set the filepath in the second query. I have two main problems with this:
I don't know any PHP so I have no idea how clicking a link could run another query and generate a new table with results.
This is important to point out, filepath is a string of a Windows path, therefore it contains backslashes like this: C:\something\something etc. When I query this manually in phpMyAdmin I escape the backslashes by writing C:\\something\\something but when getting my result in the table from the code above, the string filepath will have one pair of backslash of course (as it is saved in the database). How could I then perform my second query if the backslashes apparently need to be escaped?
Any help is very appreciated!

I thought you want to download a file. well this is much simpler:
if (isset($_GET["path"])) {
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB WHERE filepath = ?");
mysqli_stmt_bind_param($stmt, "s", $_GET["path"]);
}else{
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB");
}
mysqli_stmt_execute($stmt);
if ($result = mysqli_stmt_get_result($stmt)) {
if(mysqli_num_rows($result) > 0){
...
oh and one more thing you should escape query component in your URL
echo "<td><a href='http://mysecreturl.com/test.php?path=" . urlencode($row['filepath']) . "'>" . $row['filename'] . "<a/></td>";

Now this could be done using get method like <a href="yourpage.php?path='your_filepath'"> then in your php use this <?php if(isset($_GET['filepath'])){//Run your php query here}?>

You can do something like this:
echo '<tr>
<td><form method="get" action="test.php">
<button type="submit" name="path" value="'.$row['filepath'].'">
'.$row['filename'].'</button>
</form></td>
<td>'.$row['filepath'].'</td>
<td>'.$row['size'].'</td>
</tr>';
Untested, but should in theory work. Why you have the link in the filename-table-cell, instead of in the table-cell with the actual path in it, god knows, but you can test it and see if it works.
I would, however, just make this into a $_POST, unless it's important to show the URI in the address bar.

To answer the first question, you can add variables to a link, e.g. if you want to pass a first name and last name in a link you would do this
<?php
$fname = "John"; // First name
$lname = "Doe"; // Last Name
echo "<a href='next_table.php?fname=$fname&lname=$lname'>Next Table</a>";
?>
Then to retrieve the first name and last name on another page you would use this:
<?php
$fname = $_GET["fname"];
$lname = $_GET["lname"];
?>
Let me know if this helps.

Just an if statement to check whether the filepath is set or not and str_replace function to escape backlashes.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
// Check If filpath is set or not
if(!isset($_GET['filepath']))
{
$sql = "SELECT * FROM fileDB";
}
else
{
$filepath=$_GET['filepath'];
//replace backlashes with double backlashes using str_replace
$filepath=str_replace('\\','\\\/',$filepath);
$sql = "SELECT * FROM fileDB WHERE filepath='$filepath'";
}
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

Change the code:
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
To:
// Attempt select query execution
if(isset($_REQUEST['file']) && $_REQUEST['file'] !='') {
$sql = "SELECT * FROM fileDB WHERE `file` = '".$_REQUEST['file']."';";
} else {
$sql = "SELECT * FROM fileDB";
}
if($result = mysqli_query($link, $sql)){
This should convey the basic idea, but take to heart about using parameterized queries.

Related

Two many records showing when h_id is identified

I am trying to filter a mysql table using PHP, My aim is when the url is History.php?h_id=1 it only shows the rows that have one in the h_id (H_id is not a unique number)
My code is as below.
<html>
<head>
<title></title>
</head>
<body >
<?php
mysql_connect('localhost', 'root', 'matl0ck') or die(mysql_error());
mysql_select_db("kedb") or die(mysql_error());
$h_id = (int)$_GET['h_id'];
$query = mysql_query("SELECT * FROM Hist WHERE H_ID = '$h_id'") or die(mysql_error());
if(mysql_num_rows($query)=1){
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
?>
<?php
$con=mysqli_connect("localhost","root","matl0ck","kedb");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Hist");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>H_ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['DateMod'] . "</td>";
echo "<td>" . $row['H_ID'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I try to use this it shows all records that has a number in the h_id when I delete a number in this column it shows an error.
My table layout is as below.
Thank you
This is your syntactically incorrect statement
if(mysql_num_rows($query)=1){
A test is done using == and = is a value assignment
if(mysql_num_rows($query) == 1){
//------------------------^^
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
Also
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements and therefore stick to the mysqli_ or PDO database extensions
Your general code seemed to get a bit confused, and you were getting data from a query "SELECT * FROM Hist" that you never seemed to use.
Also the while loop was being terminated before you actually consumed and output the results of the first query.
I also amended the code to use parameterized and prepared queries, and removed the use of the mysql_ which no longer exists in PHP7
<?php
// Use one connection for all script, and make it MYSQLI or PDO
$con=mysqli_connect("localhost","root","matl0ck","kedb");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// if connection fails there is no point doing anything else
exit;
}
//$h_id = (int)$_GET['h_id'];
// prepare and bind values to make the code safe from SQL Injection
// also only select the rows you want
$sql = "SELECT ID, Name, DateMod, H_ID FROM Hist WHERE H_ID = ?";
$stmt = $con->prepare($sql);
if ( ! $stmt ) {
echo $con->error;
exit;
}
$stmt->bind_param("i", $_GET['h_id']);
$stmt->execute();
if ( ! $stmt ) {
echo $con->error;
exit;
}
// bind the query results 4 columns to local variable
$stmt->bind_result($ID, $Name, $DateMod, $H_ID);
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
if($con->affected_rows > 0){
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
while($stmt->fetch()) {
while($row = $stmt->fetch_array()) {
echo "<tr>";
echo "<td>$ID</td>";
echo "<td>$Name</td>";
echo "<td>$DateMod</td>";
echo "<td>$H_ID</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo 'No entry found. Go back';
}
?>

In my php script, my connection to the server works but my sql queries do not

The connection works, I don't get a connection error. But when I run the script I get an undefined index error and it outputs "0 results" although my table is populated for sure and I am searching for something that I know is in the table.
I am using MySQL workbench to manage the database and apache (xampp) to host the local server and run the PHP scripts. Could this be the problem? Is there a way for me to host the database in the same place as the apache website?
$sql="SELECT * FROM book_table WHERE Title LIKE $input OR Author LIKE $input OR Barcode LIKE $input";
$result = $conn->query($sql);
if ($result) {
while($row = $result->fetch_all()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
My suggestion to you is PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM book_table WHERE Title LIKE :info OR Author LIKE :info OR Barcode LIKE :info";
$ps = $db->prepare($query);
$ps->bindValue(':info', $input)
$ps->execute();
$result = $ps->fetchAll(PDO::FETCH_ASSOC);
//iterate over result
if (!empty($results)){
foreach ($result as $row) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
Also, remember to use the MySQL LIKE in the right way. When you want to match a part of a String, you need to use the % symbol.
Ex:
SELECT * FROM book_table WHERE Title LIKE "%goodbook%"
It will return all rows that has the "goodbook" as part of the Title.
You can try like this. Since you use mysqli_* I have make it prepared statements and bind_param.
Note: Not tested. So may need to adjust a bit.
$param = '$input';
$sql= $conn->prepare("SELECT * FROM book_table WHERE Title LIKE ? OR Author LIKE ? OR Barcode LIKE ?");
$sql->bind_param("s", $param);
$sql->execute();
if($res->num_rows > 0) {
while ($row = $res->fetch()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}

Produce dynamic link from array

I have a searchpage, which works fine. Search results are displayed in a table with tr hover and a window.location to take the user to a different page.
What I am trying to achieve is a dynamic link for the window.location based on data from the array. All the data in the db belongs to 4 different categories, testkat, and I would like to direct the user to the right page depending on the value from testkat, and then using the 'testid' to fill in the data.
I have been trying numerous ways to achieve my goal, and searched both SE, Google etc, but no luck. I'm pretty new to PHP so using the right search term might have something to do with it.
From my point of view I'm thinking that I have to store the value from testkat in a variable, lets say $link. And from there make an IF statement, something like:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
if ($results('testkat') == 'something_else') {
$link = "something_else.php?id='$testid'";
}
And from there put $link in the window.location
Here's my code:
<?php
$conn = mysql_connect("localhost", "root", "") or die("Couldn't do it: ".mysql_error());
mysql_select_db("db") or die(mysql_error());
mysql_set_charset('utf8',$conn);
$query = $_POST['query'];
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM db WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`age` LIKE '%".$query."%')") or die(mysql_error());
$count = mysql_num_rows($raw_results);
if(isset($_POST['query'])) {
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $count . " hits";
echo "<br>";
if(mysql_num_rows($raw_results) > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
echo "<tr class=\"tablelist\"><th>Heading 1</th><th>Heading 2</th><th>#</th><th>Heading 3</th><th>Heading 4</th><th>Heading 5</th>";
while($results = mysql_fetch_array($raw_results)){
echo "<tr onclick=\"window.location='#'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$results['testid'] . "</td>";
echo "<td class=\"bordered\">" .$results['testkat'] . "</td>";
echo "<td class=\"bordered\">" .$results['intnr'] . "</td>";
echo "<td class=\"bordered\">" .$results['pro'] . "</td>";
}
echo "</table>";
}
else{
}
}
?>
Update:
Forgot to tell about the error. When doing it the way I think it should be done, I get an error message in the IF statement saying: Fatal error: Function name must be a string.
Referring to this one:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
I know about MySQLi and PDO, working on it.
Eager to learn, so any hints and tricks are greatly appreciated :)
Chris
That method looks fine. You don't need the single quotations around $testid though
$link = "something_else.php?id=$testid";
As you've mentioned you should stop using mysql, get learning :)
Managed to fix it, and posting if someone else are having the same problem.
First, rewrote the whole thing to MySQLi.
Then I put an IF statement after the WHILE LOOP like this:
Connecting to db ->
if(isset($_POST['query'])) {
$query = $_POST['query'];
$query = htmlspecialchars($query);
$sql = $db->query("SELECT * FROM db WHERE (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%')");
$result = mysqli_query($db, sql);
$hits = $sql->num_rows;
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $hits . " results";
echo "<br>";
if($sql->num_rows > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
while ($row = mysqli_fetch_array($sql)) {
if ($row['category'] == 'cat01'){
$link = 'cat01.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat02'){
$link = 'cat02.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat03'){
$link = 'cat03.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat04'){
$link = 'cat04.php?id=' . $row['testid'] . '';
}
echo "<tr onclick=\"window.location='$link'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$row['testid'] . "</td>";
>>> more echo
}
There are probably more efficient ways to do this, but at least I got the results I was after, and the script is also more secure now using MySQLi

Import data from a txt file in a MySQL database with PHP on visit

I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

How can I get a results page using bind params to return query from drop down

I'm working through an online tutorial to rewrite my results page using bind params. I thought I understood it fairly well but I can't get it to work so obviously, I don't. I've tried everything I thought logical plus some things that were not but still all I get is a blank page.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli(localhost,user,password,database);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select name="dropdown">
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" />
</form>
And this is the results page.It is pretty much copied from the tutorial except in the tutorial $queryparam would have been equal to $_POST['Country']. As that didn't work I've changed it to $_POST['dropdown'] which is the name of the drop down.
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown']){
}
$stmt=mysqli_prepare($connection,"SELECT Key, Country, Year, Description, Images FROM engravers WHERE Country=?");
$queryParam=$_POST['dropdown'];
mysqli_stmt_bind_param($stmt,"s",$queryParam);
mysqli_stmt_bind_result($stmt,$Key,$Country,$Year,$Description,$Images);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$img_url = "http://www.engravedstamps.net/images/";
print '<table border="1" >';
while($row ->mysqli_stmt_fetch($stmt);
{
print '<tr>';
print '<td>'.$row["Key"].'</td>';
print '<td>'.$row["Country"].'</td>';
print '<td>'.$row["Year"].'</td>';
print '<td>'.$row["Description"].'</td>';
print '<td>'.'<img src="'.$img_url.$row['Images'].'" />'.'</td>';
print '</tr>';
}
print '</table>';
$results->free();
$mysqli->close();
I want to get this working but I also want to know why things work or don't.
Since writing the above, I've found a much neater way to do this which is working so for any other newbies like me, this is the code. The first lines to connect to the database are the same. then...
if(isset($_POST['dropdown'])){
}else{
echo "No input";
}
$stmt = $mysqli->prepare("SELECT ID,Country,Year,Description,Images FROM engravers WHERE Country = ? ORDER BY ID");
$stmt->bind_param('s', $_POST['dropdown']);
$stmt->execute();
$stmt->bind_result($ID,$Country,$Year,$Description,$Images);
$img_url = "http://www.engravedstamps.net/images/";
print "<table border='1' cellpadding='0'>";
while ($stmt->fetch()){
print '<tr><th>ID</th><th>Country</th><th>Year</th><th>Description</th><th>Image</th></tr>';
print '<tr>';
print "<td> " .$ID." </td>";
print "<td> " .$Country. " </td>";
print "<td> " .$Year. " </td>";
print "<td> " .$Description." </td>";
print '<td>'.'<img src="'.$img_url.$row.$Images.'" />'.'</td>';
?>
<td><a href="more.php?ID=<? echo $ID;?>">More Details</td>
<?
print '</tr>';
}
print '</table>';
$stmt->close();
?>
Tha hardest part was getting it to print into a table. There is also a cell now which offers more details for each line. If you click it, it takes you to a new page. I hope this can be of use to someone.

Categories