I am trying to retrieve values from the database using mysql and PHP.
The problem is :
+++ My table field (product_model_name) consist of (;) e.g Crystal;Uni and i want to filter results according to this product range.
I have tried to use mysql_real_escape_string() to deal with it but couldn't succeed.Here is my code:
$range="Crystal;Uni";
$test=mysql_real_escape_string($range);
$sql="select product_model_image from product_models where product_model_name=".$test;
$res= mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_array($res))
{
echo $row['product_model_image '];
}
Can anybody point me where i am making mistake??
try
$sql="select product_model_image from product_models where product_model_name= '{$test}'";
also use the pdo or mysqli instead mysql_*
Here is good PDO tutorial
Wrap your string in quotes in the query:
$sql="select product_model_image from product_models where product_model_name='".$test."'";
Obligatory side note: mysql_* library is being phased out so you should write new code in another library such as PDO or MySQLi. There are many other benefits to these libraries anyway, such as parameterised queries which are more secure than escaping as you are doing now.
Related
I´m new in PHP and I´ve realised that my database connection, using a php form (with user and pass text inputs) was totally unsafe:
This was working, but was unsafe:
<?php
$link=mysqli_connect('localhost','xx','xx','xx');
$sql=' SELECT * FROM usuarios
WHERE username="'.$_POST['usuario'].'"
AND pass="'.$_POST['usuario'].'"
';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>
So, I´ve read about mysqli_real_escape_string, and decided to try it out:
<?php
$link=mysqli_connect('localhost','xx','xx','xx');
$usuario=mysqli_real_escape_string($link, $_POST["usuario"]);
$clave=mysqli_real_escape_string($link, $_POST["clave"]);
$sql=' SELECT * FROM usuarios
WHERE username="'.$usuario.'"
AND pass="'.$clave.'"
';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>
Is this correct? Is this a good example of how to use mysqli_real_escape_string?
Is this correct?
Yes. This isolated handpicked example is safe. It doesn't mean, though, that mysqli_real_escape_string should be viewed as a function that's purpose is to prevent SQL injections. Because in this example it protects you only by accident.
Is this a good example of how to use mysqli_real_escape_string?
Not at all
This function should be abandoned in favor of using parameters in the query. This function will fail you with any query part other than a string literal. And can be even simply overlooked.
A placeholder, also called a parameter, have to be used instead, to represent the data in your query:
$sql='SELECT * FROM usuarios WHERE username=?';
$stmt= $conn->prepare($sql);
$stmt->bind_param("s", $_POST['usuario']);
$stmt->execute();
$rs = $stmt->get_result();
See other examples in my article on the correct use of mysqli
If ever used, this function MUST be encapsulated into another function that does both escaping AND adding quotes, just like PDO::quote() does. Only this way it will be safe.
The use of mysqli() functions should only be reserved for framework developers and others who are aware of all the safety issues it can bring. For everyone else, there's PDO. It's just as easy to use as mysqli(), and far safer.
Yes you will use it save now.
The nice thing about using mysqli is that it is Object oriented.
So you can use it like this:
<?php
$mysqli = new mysqli("host", "user", "password", "database");
$usuario = $mysqli->real_escape_string($_POST["usuario"]);
$clave = $mysqli->real_escape_string($_POST["clave"]);
$sql=' SELECT * FROM usuarios
WHERE username="'.$usuario.'"
AND pass="'.$clave.'"
';
$mysqli->query($sql);
$mysqli->close();
?>
Or you can use PDO.
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>";
}
$id = $_GET['id'];
$result = mysql_query("select Count(id='$id') As Total from topics");
The above code is only working if we put count(id) but i want to get count of selected variable. How to insert id='$id' in count function it is not working please help related this.
You want a where clause in your sql query, which I believe would look like this:
select count(id) As Total from topics where id='$id'
note: depending on what type of column you have for your id field, you might need to drop the single quotes.
Warning
your code is vulnerable to sql injection you need to escape all get, post and request and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Your question isn't very clear but perhaps you're looking for COUNT CASE WHEN id = $id THEN 1 ELSE 0 END (you can even skip the ELSE 0 part I believe).
What actually are you trying to do is pretty unclear in the Question.
But if you are trying to count the number of rows then simple select count(*) as Total where {your condition} from table will will do for you.
$id get values of $_GET['id']
if you want other data, use $id="your data here"
The following should work:
$id = $_GET['id'];
$result = mysql_query("SELECT COUNT(`" . $id . "`) AS `Total` FROM `Topics`");
But do note that this isn't very secure since it will be vulnerable to SQL Injection attacks.
Count can be used as below
<?php
$shoes=array("nike","puma","lancer");
echo count($shoes);
?>
Read the documentation in the PHP manual on Count.For inserting id in count:
$result = mysql_query('SELECT COUNT(id) FROM clients');
$count = mysql_result($result,0);
echo $count;
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)
When inserting a row in mysql database, string values need to be enclosed in quotes where integer don't need to.
Is there any class or library that takes care of this automatically so that I can just pass to a 3rd-party function an array of fieldnames and values and don't have to worry about putting string values in quotes?
Thanks,
You need to worry about more than just quoting; you need to worry about SQL injection.
For new code, use PDO instead of the mysql_ or mysqli_ functions. Within PDO, use prepared statements (the PDOStatement object).
With prepared statements, you never have to enclose things in quotes and it stops SQL injections.
If you use PDO, then you do not need to worry about things like that.
Take a look at PDO::prepare for some examples.
When I'm using drupal, the default behavior of db_query("SELECT col FROM tab WHERE id=%d",$id) handles that for you.
This is similar to using sprintf with mysql_real_escape_string on your query first. And you could implement it yourself, from the code they show, note that they use the preg_replace_callback() method, and you can click on that..
The traditional way, if you ignore PDO (not recommended):
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>