PHP/ SQL Query Format [duplicate] - php

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

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 ] );

How do I get artistName as a variable [duplicate]

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

Double quotes in DB breaking HTML Output

I've tried everything, and I still can't figure it out. addslahes(), str_replace(), htmlentities(), I just can't understand why double quotes are not displaying on my website.
$sql = $con->prepare("SELECT * FROM `user_settings` WHERE `user_session` = '$user_session'");
$sql -> execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$advertising_1 = $row['advertising_1'];
$advertising_2 = $row['advertising_2'];
$website_name = $row['website_name'];
$website_url = $row['website_url'];
$statistics = $row['statistics'];
}
echo '<input type="text" name="website_name" placeholder="Your Website URL" value="'. $website_name. '" />' ?>
Can someone please explain where I'm going wrong here? Problem arises with Double quotes in my string. Single quotes was fixed with mysql_escape but it appears to be deprecated.
You need to escape the data you are outputting to the browser use htmlspecialchars and use the quotes constant (ENT_QUOTES) so all quotes are converted to entities. Note this also is how XSS injections are prevented/performed. Elements/attributes are closed when they aren't suppose to be and then malicious code is written.
echo htmlspecialchars('Encode all of these "test" test \'test \'', ENT_QUOTES);
Output:
Encode all of these "test" test 'test '
and in a browser:
Encode all of these "test" test 'test '
Also from the code you displayed you are misusing prepared statements. Values need to be bound, not concatenated to your query. This way the PDO driver will handle the quoting/escaping. This could result in similar issues for you in the future, if you continue to use it as you have it. Also opens you to SQL injections.
For more information on prepared statements see: http://php.net/manual/en/pdo.prepared-statements.php
You need to use the prepare without variables on the statement and later you add them on the execute() as an array, like this:
$sql ="SELECT * FROM `user_settings` WHERE `user_session` = ?";
$stmt = $con->prepare($sql);
$stmt->execute([$user_session]);

How to deal with apostrophes and double quotes simultaneously in PHP

I have a HTML form, from which a PHP script extracts values, as shown below:
$dbc = mysqli_connect("all required info here...") or die("Error occurred");
$sent = "Any sentence here...which may contain apostrophe or double quotes or both";
$query = "SELECT * FROM myrecord WHERE sentence = '$sent'";
$result = mysqli_query($dbc, $query);
$data = mysqli_fetch_array($result);
mysqli_close($dbc);
The problem is, that the variable $sent can contain any string with a combination of either apostrophe or double quotes or both. This gives an error when going for execution of mysqli_query().
So even if I escape double quotes in initialization of $sent it will still create problem for execution of mysqli_query(). And if I escape both for ' and " then value of $sent does not remains what it actually needs to be (although I am not sure about whether escaping both ' and " will work or not).
Is there any built in function that automatically escapes all special characters of a string? Or any workaround that solves this problem?
[P.S. I have already searched some previous questions on stackoverflow and haven't been able to find a solution.]
What you want, and what you should do is used prepared statements (parameterized queries). With PDO, that would look something like this:
$stmt = $pdo->prepare('SELECT * FROM myrecord WHERE sentence = :sentence');
$stmt->execute([':sentence' => $sentence]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//do stuff
}
mysqli supports them, too, but the API is slightly more cumbersome (IMO) - see mysqli_prepare docs for details:
$stmt = $mysqli->prepare('SELECT * FROM myrecord WHERE sentence = ?');
//or $stmt = mysqli_prepare($connection, $query);
Then, you bind the parameter (the value to be used in the WHERE clause) using bind_param:
$stmt->bind_param('s', $sentence);
//or mysqli_stmt_bind_param($stmt, 's', $sentence);
Then call execute - or mysqli_stmt_execute, and fetch the results using fetch - or mysqli_stmt_fetch...
As mentioned in the comments: the parameters and query string needn't be quoted in any way, because they're treated as separate entities. The result being that you can re-use the same prepared statement with different paramters:
$stmt = $pdo->prepare('SELECT * FROM table WHERE field = :field');
$fieldVals = [123, 46, 32]; // three values:
$results = array_fill_keys($fieldVals, null);
foreach ($fieldVals as $val) {
$stmt->execute([':field' => $val]);//execute with each value in $fieldVals array
$results[$val] = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch results for this field value
//optional, but good form:
$stmt->closeCursor();
}
you've now used the same statement 3 times, but only had to send the query string once. The query had to be parsed and processed once, and after that, you merely sent the paramters to the DB. This approach is generally faster, safer (prepared statements protect agains most injection attacks), and just all round better.

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

Categories