How do I get artistName as a variable [duplicate] - php

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I was wondering if it was possible to get a value from mysqli query and use it in the same page, if so how would I do that here?
$sql2 = "select artistName from ARTIST";
$result2 = $conn->query($sql2);
if($result2->num_rows != 0){
echo "<p>Artist: <select artistname=\"artistName\">";
while ($val2 = $result2->fetch_assoc()) {
echo "<option value='$val2[artistName]'>$val2[artistName]</option>";
}
echo "</select></p>";
}
I am trying to make this request below:
$addArt = "update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'";
where filename is an arbitrary file

Multiple issues:
Mixed quotes:
"<option value='$val2[artistName]'>$val2[artistName]</option>"
"update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'"
Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Reference: https://www.php.net/manual/en/language.types.string.php
SQL Injection
"update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'"
You need to be careful with how you get the value $val2[artistName] else it may lead to SQL Injection attack

Related

Using str_replace in table query in MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
If you create a variable inside a if statement is it available outside the if statement?
(4 answers)
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
If variable equals value php [duplicate]
(4 answers)
Closed 2 years ago.
There are a lot of examples on SO of using str_replace to modify a query that uses variables in MYSQL but I can't find one that solves my problem.
I have the following legacy query that I'm debugging written in PHP and MySQL.
Somewhat simplified it is:
$sql = "SELECT * from MOVIES WHERE cat = '$cat'";
In the event that cat has a certain value, say, "action" I want to check for "adventure";
Let's say you start with query:
$cat = "action";
$sql = "SELECT * FROM MOVIES WHERE cat='$cat'";
I'm trying to modify the query with:
$needle = "cat=".$cat;
$altcat = "adventure";
$altwhere = "cat=".altcat;
$sql = str_replace($needle,$altwhere,$sql); //NOTHING GETS REPLACED...NOT MATCHING Needle
How can I do this? I'm thinking the problem has something to do with use of spaces or apostrophes in the sql string but can't get it to work.
Thanks for any suggestions.
You want to replace "cat='".$cat."'" with "cat='adventure'", not "cat=".$cat with "cat=adventure".
(Though you are inconsistent in saying if there are spaces around the =.)
But you should not do this and should use a placeholder instead.
I would not try to do string substitution on the SQL query. Instead, just use query parameters.
$cat = 'action'; // suppose this is the input to your program
$sql = "SELECT * from MOVIES WHERE cat = ?";
if ($cat == 'action') {
$cat = 'adventure';
}
$stmt = $db->prepare($sql);
$stmt->execute( [ $cat ] );

PHP/ SQL Query Format [duplicate]

This question already has answers here:
How to escape apostrophe (') in MySql?
(10 answers)
Closed 6 years ago.
I'm having trouble running a query from an AJAX call. It's just updating a row in my table with an HTML string for later use. I think it has to do with my quote format but for some reason my brain is not wrapping around the correct order. Also, I realize I should probably escape those values before I run them through the query. Nevertheless, still stuck :(
$trackingNumber = $_POST['trackingNumber'];
$formValue = $_POST['formValue'];
$query = "UPDATE number_pairs SET custom_tags = '<button class='edit customTag' type='button' value='.$trackingNumber.'>.$formValue.<i class='fa fa-tag' aria-hidden='true'></i></button>' WHERE tracking_number = '$trackingNumber'";
Put the value for custom_tags on a separate variable like this:
$tags="<button class='edit customTag' type='button' value='$trackingNumber'>$formValue<i class='fa fa-tag' aria-hidden='true'></i></button>"
Remember, single quotes can exist inside double quotes. You can also place the $trackingNumber and $formValue variables inside a double-quoted string and everything will work with PHP's string interpolation.
After that you should use either mysqli or PDO to bind the parameter to the query.
MySQLi
$query = "UPDATE number_pairs SET custom_tags=? WHERE tracking_number=?";
$db = new mysqli(<YOUR DATABASE INFORMATION HERE>);
$stmt = $conn->prepare($query);
$stmt->bind_param("si", $tags, $tracking_number);
$stmt->execute();
PDO
$query = "UPDATE number_pairs SET custom_tags=:ct WHERE tracking_number=:tn";
$conn = new PDO(<AGAIN, YOUR DB CREDENTIALS HERE>);
$stmt = $conn->prepare($query);
$stmt->bindValue(':ct', $tags);
$stmt->bindValue(':tn', $tracking_number);
$stmt->execute();
you need to escape at least your quote/ticks signs for the HTML attributes in your value.
Like (untested):
$query = "UPDATE number_pairs SET custom_tags = '<button class=\'edit customTag\' type=\'button\' value=\'$trackingNumber\'>$formValue<i class=\'fa fa-tag\' aria-hidden=\'true\'></i></button>' WHERE tracking_number = '$trackingNumber'";
The second thing is, that you wrap your SQL string with double quotes but trying to concat SQL query parts with variables with '.$varablenamehere.' . I removed the '. and .' in the code sampel above. The content of the variables will be placed into the string anyway, because the whole string is wrapped with double quotes. For more information: PHP: Using a variable inside a double quotes

Sql injection get id solution [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I don't know how to make this code safe. I tried to use mysql_real_escape_string in the query variable like
$query = "select * from products where id= " . mysql_real_escape_string($products);
but didn't work, also tried to escape in the products variable, but got the same result.
Any sugestions?
Thanks.
<?php
/ Define vars.
$conn = mysql_connect('localhost', 'test', 'test');
$products = isset($_GET["products"]) ? $_GET["products"] : "";
$query = "select * from products where id=$products";
// List elements.
if ($conn)
{
mysql_select_db('testsqli');
$result = mysql_query($query);
// Table head.
echo '<table cellspacing="5" cellpadding="5">';
echo '<tr>';
echo '<td>Description</td>';
echo '<td>Price</td>';
echo '</tr>';
// Empty table?
if (#mysql_num_rows($result)==0)
{
echo '<tr>';
echo '<td><i>That\'s all!</i></td>';
echo '</tr>';
}
// Listing data in table.
while ($row = #mysql_fetch_array($result))
{
echo '<td>'.$row['Description'].'</td>';;
echo '<td>'.$row['Price'].'</td>';;
}
echo '</table>';
}
?>
You still need to add quotes, (and use msqli instead) like:
$query = "select * from products where id='" . mysqli_real_escape_string($products)."'";
// or
$query = sprintf(
"select * from products where id='%s'",
mysqli_real_escape_string($products)
);
I'd use prepared statements instead of MySQL escaping. Escaping skips over some of the wildcards, such as '%' and '*' which could also provide unanticipated results.
$stmt = $dbh->prepare("SELECT * FROM PRODUCTS WHERE ID=?");
$stmt->bindParam(1, $products, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
Also, keep in mind the following measures keep it safe:
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type. (In this case, verify that $products is formatted as expected, i.e. if your product catalog has indices of only nine characters, make sure it's not 100 characters long.) PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().
Reference: http://php.net/manual/en/security.database.sql-injection.php

php sql query function syntax not working [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 10 years ago.
I'm was trying to get my function to work and after a while I slammed my keyboard down and then everything worked and I noticed that:
{
function get_people_fullname($db, $people_id) {
$query = 'SELECT
people_fullname
FROM
people
WHERE
people_id = '.$people_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
return $row['people_fullname'];}
}
where there query goes
people_id = '.$people_id;
which works
I originally had
people_id = $people_id';
which doesn't work
I'm just lost and I think this is a simple thing someone more experienced can explain this to Me?
thanks
you need to use double quotes in order to get the value of the variable,
$query = "SELECT
people_fullname
FROM
people
WHERE
people_id = $people_id";
in php, let's say $a = 5,
echo 'a is $a'; // will result: a is $s
echo "a is $a"; // will result: a is 5
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
single quotes do not have variable substitution - double quotes is what you want if you want to replace $var with a value

mysql_query error with single quotes in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I handle single quotes inside a SQL query in PHP?
I had written the following code to fetch a data from a mysql table:
$clg=$row['text'];
$query1 = "SELECT * FROM user WHERE text='$clg'";
$result1 = mysql_query($query1,$con) or die(mysql_error());
$count=mysql_num_rows($result1);
echo $count;
But the text field has a single quote(') which closes the single quotes in $query1, hence resulting in mysql syntax error. How can I rectify this?
$clg=$row['text'];
$query1 = "SELECT * FROM user WHERE text='" . mysql_real_escape_string($clg) . "'";
$result1 = mysql_query($query1,$con) or die(mysql_error());
$count=mysql_num_rows($result1);
echo $count;
But you should know that mysql_* functions family will be deprecated soon.
Please read the red box here located on php.net website.
<?php
function escape($string) {
if(get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
write this function and call it
escape($clg);
for prevent every mysql syntax error and sql injection.`

Categories