How to get MySQL select query values into a PHP variable? - php

I know I need to use the MySQL fetch to prevent getting a resource ID in my variable but I wondered if you could help me out how to do that. I see from several tutorials they use a loop but I just want to select the one string into a variable. Here is the code I have:
$img = mysql_query('SELECT pname FROM photos WHERE pphotoid=21');
echo $img;
I basically want $img to contain the string in the database not Resource id #3 it is currently showing. Also is what I wrote prone to an SQL injection?
Learning MySQL so any help would be great!

$img=mysql_fetch_assoc(mysql_query('SELECT pname FROM photos WHERE pphotoid=21'));
echo $img["pname"];
Better would be
$img=mysqli_fetch_assoc(mysqli_query($link,'SELECT pname FROM photos WHERE pphotoid=21'));
echo $img["pname"];

$handle = mysql_query('SELECT pname FROM photos WHERE pphotoid=21');
$row = mysql_fetch_row($handle);
echo $img[0];
http://pl1.php.net/mysql_fetch_row
this code will work for you.
To prevent SQL injection you should use escape functions like mysql_escape_string()
you should also check what is your input and valid it
here you will learn more
How can I prevent SQL injection in PHP?
also it's better to use PDO because mysql_* are deprecated as of PHP 5.5.0, and will be removed in the future.
here is tutorial to learn connecting to db with PDO
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
your code in PDO(assuming you are connected to db) will look like:
$id = intval(21); //this code here is senseless however if you get 21 for example via $_GET it will cast it to integer and prevent injection
$stmt = $db->prepare("SELECT pname FROM photos WHERE pphotoid=?");
$stmt->execute(array($id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['pname'];

I like the following:
connection.php:
//All the $*_db variables are pulled from a file kept outside of the document root directory but referenced here to connect to the database
include('/path/to/file/not/in/docroot/connection_info.php');
$DBi = mysqli_connect($hostname_db, $username_db, $password_db, $database_db);
if($mysqli->connect_error) {
//Do something for errors here...
};
file.php
include('connection.php');
$q_myQuery = "SELECT `pname` FROM `photos` WHERE `pphotoid` = 21";
$rsmyQuery = mysqli_query($DBi, $q_myQuery) or die(mysqli_error($DBi));
$row_rsmyQuery = mysqli_fetch_assoc($rsmyQuery);
$img = $row_rsmyQuery['pname'];
That's using mysqli* functions, not mysql* which have been deprecated. More on that here: http://us3.php.net/manual/en/mysqlinfo.api.choosing.php

Related

PHP not showing MySQL results with variable in query [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

PHP search only showing one result from SQL

Im using a PHP search function on my website and it is currently only displaying one result from my SQL database - i would like it to display all results included in the site_keywords!
Here is the PHP code i'm currently using on my page
<?php
mysql_connect("danieljosephdesignsc.ipagemysql.com", "searchdata", "danieljoseph");
mysql_select_db("my_db");
if(isset($_GET['search'])) {
$search_value = $_GET['value'];
$query = "select * from sites where site_keywords like '%$search_value%'";
$run = mysql_query($query);
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
}
?>
Here is what is included in my body:
<?php echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";?>
Please let me know if you require further info. Any assistance on this would be greatly appreciated.
Thanks
You problem is that you aren't echoing the results within your loop.
you need something like this:
while($row=mysql_fetch_assoc($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}
Important Note:
You are using deprecated code. This is true of any function that begins with mysql_. This means that your code will no longer work in newer versions of php, and is likely to be not secure if you call any of your variables in your queries. You really need to look up using prepared statements using either mysqli or PDO.
From the official site
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. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
Here's how to use mysqli prepared statements
or PDO prepared statements
The problem is in this block of code:
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
Even though you're getting multiple results, each result overwrites the values of the previous one. So in the end you only have a single row. Try saving the results to an array instead and iterating over it in the body.
$rows =array();
while($row=mysql_fetch_array($run)){
$rows[] =$row;
}
foreach($rows as $row){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}

Am I doing the mysqli right? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Every question which I asked on stackoverflow I received a question that It was easy to do a php injection into my script.
I've now a example and checked some tutorials on youtube.
Am I doing this right now?
This is an example how I'm working now
if($user->isLoggedIn()) {
$pakuser = $user->data()->username;
$sql = $db->query("SELECT * FROM users
INNER JOIN post ON users.username = post.add
WHERE post.id = $id AND post.add = '$pakuser'")
or die(mysql_error());
if ($sql === FALSE) {
}
if($row = $sql->fetch_object())
if($row->add)
{
?>
<p>edit this post<br><br>BEWARE OF DELETING YOUR CONTENT THERE IS NO GO-BACK<BR>Delete this post </p>
<?php
}
}
Everytime the user can manipulate your sql-query without any restriction, there is a security-issue. Here is an example:
$query_string = "SELECT * FROM user WHERE (name='$username' AND password='$password')";
if the user sends a password like:
"something') OR ('1' = '1"
the query will change to:
$query_string = "SELECT * FROM user WHERE (name='Name' AND password='something') OR ('1' = '1')";
Because '1'='1' is always true, this will return each user in your database.
Instead you can change the example above to:
$query = mysqli->prepare('SELECT * FROM user WHERE (name=? AND password=?)');
$query->bind_param('ss', $username, $password);
$query->execute();
This will filter all strings that could break your sql-query.
It seems like you are still just passing variables straight through into the query. Yes, this may work, but is not necessary secure.
You could have a look at using PDO instead, which has means of being able to verify the data type that you are wanting to pass through into your query rather than just passing a variable into the query string.
In terms of using mysqli, have a look at mysqli_real_escape_string if you have not already. It is well documented.

PHP delete values from mysql bad

I have a script which works without errors, but can't delete chosen value from mysql.
It looks like: What problem could be?
include('opendb.php');
$a = $_GET['new_pav'];
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
Firstly, read this (and below):
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
The red warning box is telling you to stop using mysql_* in anything new.
As for your query, DELETE FROM x WHERE y=z is a valid query, so the error could be from your use of quotes (if new_pav is an int, then this could explain it); strings are quoted in MySQL.
Also, do not interpolate/concat strings in an SQL query, or you risk SQL Injection. Look up pdo, and start using classes for something that involves a state (the db connection), rather than a variable and countless functions. (I originally used mysqli here):
try {
$db = new PDO("mysql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass);
$query = $db->prepare("SELECT COUNT(*) FROM naujiena WHERE new_pav = :pav");
if (!$query->bindParam(":pav", $_POST["new_pav"])) {
die("Input incorrect; couldn't bind");
}
$query->execute();
$rows = $query->fetchColumn(0); // fetch a single column. count(*) here.
if ($rows !== 0) { // It has a result~
$query = $db->prepare("DELETE FROM naujiena WHERE new_pav = :pav");
$query->execute(array(":pav" => $_POST["new_pav"]));
}
$db = null; // explicitly close connection
} catch (PDOException $e) { // catch any exception PDO throws at you.
// note that you should catch where appropriate.
die("Connection Failed: " . $e->getMessage());
}
Note that with SQL Injection, I could type ' OR 1=1 -- and delete your whole table.
As you can see, this is far from a one/two-liner, but you must never trust anything added to SQL that you didn't hardcode in yourself, period.
Apart from using mysql_ libraries your code:
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
In the SELECT you are not escaping the value of $a but in the delete you are escaping it.
Anyway if you are just doing a delete you do not need the SELECT or while loop. So you could use the following code:
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");

"mysql_fetch_assoc()" error when data in mysql field is changed

I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.

Categories