I am trying to create a simple link. The issue is the file name is going to come from the database.
example: Download
I have not worked much with MYSQL and have pieced together something that is working so far
<?php
$products_id = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = "select * from znc_product_extra_fields where products_id = '" . $products_id . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo $row['file_1'];
}
?>
When I run it it does just what I want, it echos the file name that is assigned to that specific row (item number)
But I am lost how to turn this into the link. The only thing I can think is somehow assigning this result to a variable and calling it while creating the link but I do not know how to take this result which is correct and actually use it! How would I take this filename and place in the link
Download
PHP outputs whatever you want it to - text, HTML, XML, etc. So just output the HTML. I think what you want is:
echo "Download";
Although you shouldn't be using the outdated mysql_* functions. Please see PDO (the best option) or mysqli.
To prevent SQL injection, use PDO::quote (if you are using PDO), or mysqli_real_escape_string (if you are using mysqli).
echo 'file;
Your code is vulnerable to MySQL injection. Use real_escape_string
on your GET, POST parameters.
You should use PDO (see tereško comment for reason)
Related
I have a problem displaying images for URLs that are saved in a database.
This is my HTML source code:
<div id="posts">
<img id="images" src="php/getImage.php?id=1">
<footer>
<a href="php/getImage.php?id=1" download><p>Download</p></a>
</footer>
</div>
And my getImage.php file:
<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>
You have multiple problems here:
1) STOP using Mysql_ functions and use ONLY mysqli_ functions (or PDO) . Mysql_ PHP funtions are deprecated and no longer supported (and hasn't been for 5+ years!). It is insecure and will only get worse.
2) Your PHP file is simply echo'ing a string, images/someimagename.jpg; this is not what an image file is, you need to output the contents of this filename string.
3) Your current SQL is prone to SQL injection and is currently extremely insecure. Your database can be easily corrupted/abused by nefarious web page visitors.
4) Your mysqli_fetch_array needs to be assigned to a variable for the values in the array to be used.
5) Use single quotes rather than double quotes for your DB authentication so that special characters (such as$) - especially in passwords - are not misinterpreted by PHP.
Solution to the above problems:
<?php
// id is assumed to be an integer value.
// This prevents SQL injection and database compromise by forced
// typecasting of the data to integer.
$id = (int)$_GET['id'];
$db = mysqli_connect('host', 'username', 'password', 'DB name');
$sql = "SELECT image FROM images WHERE imageID=".$id." LIMIT 1";
// only use mysqli_ functions.
$result=mysqli_query($db, $sql);
// assign to a $variable
$output = mysqli_fetch_array($result);
//The [ relative :( ] URL of the resoure requested:
$file = "images/".$output['image'];
// Before the data is output we need to set the correct header so the
// browser knows what sort of file to expect.
$image_mime = image_type_to_mime_type(exif_imagetype($file));
header("Content-type: " . $image_mime);
// Grab and output the raw data in the filepath stored in the URL.
print readfile($file);
// If this is the end of thefile you should not use a closing PHP tag.
// ?>
If you do not have the PHP Exif Extension enabled there are various other (possibly more verbose) ways of ouputting the image type using fileinfo or mime_content_type.
PLEASE NOTE:
Your image URL is relative so, as the file getImage.php is in the php folder, the image requested will be in the php/images/<filename> path. If this is NOT where your images are stored, then you need to adjust your image path URL and make it either correct, or use absolute HTML pathing which is HIGHLY recommended.
The code posted with the question has used mysql_query / mysql_fetch_array which is deprecated to use in PHP anymore. Even with deprecated mysql_* version, this part
mysql_fetch_array($result);
echo "images/$result";
of posted code should be
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "images/".$row["image"];
(I haven't tested this code as PHP version in my machine is above 5.5 which doesn't support mysql_* extensions).
Each row requires being fetched from the result ($result) of SQL query. From the fetched row ($row) each cell can be accessed using the column header (image).
Try following code in getimage.php,
<?php
$id = $_GET['id'];
$db = new mysqli("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo 'images/'.$row['image'];
?>
FYI, mysqli supports both procedural and object-oriented programming paradigm. http://php.net/manual/en/mysqli.quickstart.dual-interface.php
I am writing a PHP script that is supposed to interact with a MySQL database. On my local testing server, the code echos out what it is supposed to just fine, but in the live environment, I get an error saying Fatal error: Call to a member function fetch_array() on a non-object in [file path removed for security] on line 42. Here is my code from around line 42.
$query = "SELECT " . $data . " FROM mySchemaTable WHERE incrementId = " . $something;
$result = mysqli_query($conn,$query);
$row = $result->fetch_array(MYSQL_BOTH); // This line is 42.
echo $row['0'];
break;
I noticed a few problems with your code:
Firstly, you're mixing OOP and Procedural programming with MySQLi commands. Although PHP allows this, you'll want to make that uniform throughout. If you're using $conn = mysqli_connect(parameters here); you'll want to focus on procedural (change $result->fetch_array(MYSQLI_BOTH) to mysqli_fetch_array($conn, MYSQLI_BOTH); for instance). (I would assume you're doing this, so do this ^ change)
Else, if it's $conn = new mysqli(parameters); then you'll want to make it OOP based; instead of mysqli_query($sql); you'd use $conn->query($sql);, assuming $sql contains the query you want to run.
Secondly, echo $row['0']; should be echo $row[0]; unless the row you're returning is actually named 0, in which case disregard this.
Thirdly, and as a side note, it's a bad idea to directly insert variables into SQL queries, especially if they're user generated. You should look into sanitizing input or prepared statements to protect against SQL injection attacks.
Sanitizing Input Reference: What's the best method for sanitizing user input with PHP?
Prepared Statements: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
The problem was solved without my intervention. It turns out that my code was fine as it was, but something was wrong with my host's MySQL. It's fixed now, and everything is working again.
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}
I've made a simple search-script in PHP that searches a mySQL database and outputs the result. How this works is like this:
User searches for "jack's" through a search-form.
My PHP-script GETs this search, and sanitizes it.
Then the script, with the use of SELECT and LIKE, gets the results.
The script then outputs the result to the user.
Lastly, the script tells the user that "jack's returned x results." with the help of escaping.
What I would like to ask is, am I doing it right?
This is how I sanitize before SELECTING from the database:
if(isset($_GET['q'])){
if(strlen(trim($_GET['q'])) >= 2){
$q = trim(mysql_real_escape_string(addcslashes($_GET['q'], '%_')));
$sql = "SELECT name, age, address FROM book WHERE name LIKE '%".$q."%'";
}
}
And this is how I escape before outputting "jack's returned x results.":
echo htmlspecialchars(stripslashes($q)) . " returned x results.";
Is this the correct way to do it?
By the way, I know that PDO and mySQLi is preferred as they sanitize themselves through the use of prepared statements, but I have no real experience with them whatsoever. But I would gladly take a look, if you guys could link me some newbie tutorials/explanations.
Furthermore, I heard that magic_quotes and charset could in some way or another lead to injections -- is this correct?
For some reason we need also escape a backslash too.
So, the proper code would be, I believe
if(isset($_GET['q'])){
$_GET['q'] = trim($_GET['q']);
if(strlen($_GET['q']) >= 2){
$q = $_GET['q'];
$q = '%'.addCslashes($q, '\%_').'%';
// now we have the value ready either for escaping or binding
$q = mysql_real_escape_string($q);
$sql = "SELECT name, age, address FROM book WHERE name LIKE '$q'";
//or
$sql = "SELECT name, age, address FROM book WHERE name LIKE ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($q));
$data = $stm->fetchAll();
}
}
For the output, use
echo htmlspecialchars($_GET['q']);
stripslashes not needed here.
Furthermore, I heard that magic_quotes and charset could in some way or another lead to injections -- is this correct?
magic quotes won't harm your security if you won't use them.
charset is dangerous in case of some extremely rare encodings but only if improperly set. if mysql(i)_set_charset or DSN (in case of PDO) were used for the purpose - you are safe again.
As for PDO, a tag wiki should be enough for starter, I believe
This is about as basic as it gets guys and girls.
I have a very simple script that just will not work. I call the database and test it's connection, I do a query, store the result, and print the result.
The problem is that I can't seem to use any variables in my SQL statement.
Here's the code:
<?php
$rest_name = $_GET['rest_name']; // outputs 'Starbucks'
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '$rest_name'");
/* I've also tried these as well
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '".$rest_name."'");
*/
$mark = mysql_result($test,0);
echo $_GET['rest_name'].$mark;
?>
I echoed the query and it looks fine and run fine in the database. The $rest_name variable echos fine. The $_GET['rest_name'] echos fine. I am lost and confused on this.
1 - You can start with this.
$test = mysql_query("S....") or die(mysql_error());
This way you will see what error you are getting.
2 - you might want to avoid using a variable provided by the user in your query
$rest_name = mysql_real_escape_string($_GET['rest_name']);
otherwise user can insert their own sql commands;
3 - mysql_xxx functions are being deprecated, you might want to research pdo or mysqli to see how the new methods work.
Verify that you have a valid result set returned by msyql_query
$test = mysql_query("SELECT ... ");
if (!$test) {
die(mysql_error());
}
(It's possible you aren't connected to the MySQL instance, you are in the wrong database, the user you are connected as doesn't have permissions, etc.)
Check the resultset, before you use it.
NOTE: Don't use the mysql_ functions, use mysqli or PDO instead.