Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code:
$list_summoners = $con->query("SELECT * FROM verified_users WHERE Username='" . $search_user . "'");
and I was wondering how I could format it, like:
$list_summoners = mysqli_query($con, "SELECT * FROM verified_users WHERE Username='" . $search_user . "'");
echo '<table align="center" style="text-align:center;"><tr><th>User</th><th>Summoner ID</th><th>Summoner Region</th><th>View Summoner</th></tr>';
while($row = mysqli_fetch_array($list_summoners)) {
echo '<tr><td>' . $row['username'] . '</td><td>' . $row['summoner_id'] . '</td><td>' . $row['summoner_region'] . '</td><td><span class="button color_dark">View</span></td></tr>';
}
echo '</table>';
I am asking this, because I know mysqli_query is open to abuse.
Thanks in advance.
mysqli_query($con, 'SELECT...') called in procedural mode, vs $con->query('SELECT...') called in object-oriented mode perform exactly the same function. In both modes, $con is the same object - a mysqli connection object, but the MySQLi API offers two methods of interacting with it.
So, the use of mysqli_query() and $con->query() are both equally insecure when used the way you are using them, concatenating in a variable $search_user. The secure method would be to avoid mysqli_query() entirely and instead use a prepared statement:
$stmt = $con->prepare('SELECT * FROM verified_users WHERE Username = ?');
if ($stmt) {
$stmt->bind_param('s', $search_user);
$stmt->execute();
// Then bind & fetch()...
}
else echo $con->error;
See How can I prevent SQL injection in PHP for more details & examples on executing and fetching from the prepared statement.
Using $con->query() as you are, to fetch rows with a while loop you may call $list_summoners->fetch_array() as it is an object of class mysqli_result
if ($list_summoners) {
while ($row = $list_summoners->fetch_array()) {
echo '<table align="center" style="text-align:center;"><tr><th>User</th><th>Summoner ID</th><th>Summoner Region</th><th>View Summoner</th></tr>';
echo '<tr><td>' . htmlspecialchars($row['username']) . '</td><td>' . htmlspecialchars($row['summoner_id']) . '</td><td>' . htmlspecialchars($row['summoner_region']) . '</td><td><span class="button color_dark">View</span></td></tr>';
echo '</table>';
}
}
Note the addition of htmlspecialchars() to those values, when sent to output as HTML. Even if these were not originated from user input, it is an important habit to be in as it will prevent cross-site scripting when outputting values originating from user input, or values which contain characters requiring entity encoding in HTML.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am currently using PHP and SQL to throw back some paramters I enter in a form.
I can search numbers perfectly fine and it gives me the correct results but anytime I use a search like "443265dsa44dd" it displays nothing even though it's in the database.
$searchedID = $_POST['uuid'];
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '.$searchedID.'";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>" . "Contact: " . $row["contact"] . "<br>" . "Phone: " . $row["phone"] . "<br>" . "Address: " . $row["address"] . " ";
}
}
The id is a primary key and set to VARCHAR, any ideas what is happening here?
You have an error when trying to include the searchedID into the sql-string.
Either concat like this:
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '" . $searchedID . "'"
// note, the additional quotes
OR
let php parse that var for you (possible only inside double-quotes):
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '$searchedID'"
BUT
You are vulnerable to sql-injection. So use prepared statements!
I am trying to display every job record in my database and when a user clicks on a record, it will go on to display the job description for that record on a new page.
At my current state I've managed to display every job, clicking on them will direct the user to the "showjob.php?id=". My problem is that it isn't displaying information for my job.
Page with list of jobs: THIS WORKS
$results = $pdo->query('SELECT * FROM jobs');
foreach ($results as $row) {
echo '<a class="job_listing_href" href="showjob.php?id="' . $row['job_id'] . '><div id="job_listing">' . $row['job_title'] . ' '
. $row['cat_job'] . '</div><br/><br/>';
}
Page with individual job information:
$pkey = mysql_real_escape_string($_GET['job_id']);
$sql = "SELECT * FROM jobs WHERE job_id='$pkey'";
foreach ($results as $pdo) {
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}
It isn't related to my job_desc as I can implement it to my previous page and it lists it just fine. My guess is that it's something to do with my $_GET but not sure.
Also as a sidenote, I'm aware my website is vulnerable to SQL injection, I'm going to fix it soon :)
Can anyone provide a solution or put me on the right tracks?
Thank you to anyone spending the time helping me!
UPDATE
I have took everyone's suggestions - thank you, but my "showjob" page still isn't displaying anything. This is my new code:
$pkey = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM jobs WHERE job_id='$pkey'";
$results = $pdo->query($sql);
foreach($results as $row) {
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}
You're mixing MySQL APIs using mysql_real_escape_string() while being connected using PDO, so you can't use those together while connecting/querying for the same code.
Sidenote: You theoretically could with older versions of PHP, but as of PHP 7.0, the mysql_ API has been removed, so you definitely wouldn't be able to use it here if that were the case.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
"This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0."
What you need to use here is a PDO prepared statement in order to escape the data, which is what you are looking to do here.
$pdo = new PDO("...");
if(!empty($_GET['job_id'])){
$pkey = $_GET['job_id'];
$statement = $pdo->prepare("SELECT * FROM jobs WHERE job_id = :jobid");
$statement->execute(array(':jobid' => $pkey));
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// echo $row['field1'].' '.$row['field2']; //etc... taken from an example, sorry.
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}
}
else{
echo "GET is empty, check for errors.";
}
Also check for errors if you're not already doing so.
References:
http://php.net/manual/en/pdo.error-handling.php
http://php.net/manual/en/function.error-reporting.php
PDO references:
http://php.net/pdo.prepared-statements
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Footnotes:
I noticed you're using href="showjob.php?id yet you're using the $_GET['job_id'] array.
id != job_id.
That will fail you if that's what you're still using and both of those need to match.
Error reporting would have told you about that.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Other notes:
If your server does not support the mysql_ MySQL API, then error reporting would have thrown you something similar to the following:
Fatal error: Call to undefined function mysql_real_escape_string()...
The results are not showing because you have your variable names mixed up, see below revision:
Change:
$pkey = mysql_real_escape_string($_GET['job_id']);
to:
$pkey = mysql_real_escape_string($_GET['id']);
Update: You are also missing: $results = $pdo->query($sql);
You are passing the job id parameter as id. However, when fetching the id for the specific job, you're retrieving job_id out of the $_GET superglobal. $_GET['id'] instead of $_GET['job_id']should work.
PS: As Alex pointed out, actually issuing a query via $results = $pdo->query($sql) may also help. Followed by iterating over foreach($results as $row). Although there should only ever be one result ...
seems that
foreach ($results as $pdo) {
echo '<div id="job_listing">' . $row['job_title']
in foreach your are using $pdo name value, but inside using $row, use the same an tell us.
expect it help
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i have the following php:
<?php
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connection,"SELECT ID FROM tbname");
while($row = mysqli_fetch_array($result))
{
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID='$row[ID]' ");
}
mysqli_close($connection);
echo 'OK'; ?>
I want to 'corelate' the pressing of a button to update the associated row value from the table but when i use this code i get all my values updated. Can anyone help me ?
This assumes that your ajax request is passing an 'id' parameter. Note that this code is open to SQL injection attacks. I am assuming that you know how to properly sanitize your inputs and parameterize your queries to protect yourself. If you don't, Jay's answer includes some good links that you should check.
<?php
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
You have to properly identify the variable in the array and concatenate the variable in the query:
mysqli_query($connection,"UPDATE tbname SET amount = amount+ 1 WHERE ID='" . $row['ID']. "' ");
you also do not need the parentheses around the calculation in the SET clause.
Since you're selecting all of the rows in your table and then looping through all of the rows and changing the value, which is not what you want, you have to select with a filter:
SELECT ID FROM tbname WHERE *some condition is met*
Once you do that you'll be able to update a subset of your records as you desire.
Since you're using MySQLi you should learn about prepared statements for MySQLi to guard yourself from potential SQL Injection Attacks.
in addition you should employ error checking, such as or die(mysqli_error()) to your connection and queries. If not you'll have to look in your error logs to fish out any problems that you could have with these.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Im self learning mySQL and php few days and now Im stuck on this error and cant help myself. Can you look at code, Thanks!
this is error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 7
here is the page
switch($_GET['action']) {
case 'add':
switch($_GET['type']) {
case 'movie':
$query = 'INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
("' . $_POST['movie_name'] . '",
' . $_POST['movie_year'] . ',
' . $_POST['movie_type'] . ')';
break;
}
break;
}
if (isset($query)) {
$result = mysql_query($query, $db) or die(mysql_error($db));
}
I think problem may be in here
<td><select name='movie_type'>
<?php
$query = 'SELECT movietype_label FROM movietype ORDER BY movietype_id';
$result = mysql_query($query, $db) or die (mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo '<option value="' . $row['movietype_id'] . '">';
echo $row['movietype_label'] . '</option>';
}
}
?>
</select></td>
and here is print_r on
Array(
[movie_name] => asd
[movie_type] =>
[movie_year] => 2015
[submit] => ADD)
Shouldn't you be using a double quote " instead of single quote ' like below. You are mixing single and double quote.
$query = "INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
('" . $_POST['movie_name'] . "',
'" . $_POST['movie_year'] . "',
'" . $_POST['movie_type'] . "')";
Granted this is ugly, but would be surprised if it fails.
$query = "INSERT INTO
movie (movie_name, movie_year, movie_type)
VALUES
('"
. $_POST['movie_name'] . "','"
. $_POST['movie_year'] . "','"
. $_POST['movie_type'] . "')";
Also, you need to cleanse your data. Data acted upon directly from user without cleansing, or sent through proper separation of code, can, and someday will, contain sql injection.
Ugly code like the above starts to take on some beauty with mysqli and pdo, plus the parameters are safely separated, and all the moaning about injection goes away.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I get this two queries with the same variables :
$query = 'UPDATE payee SET payee="oui", datePaiement=\'' . $datePaiement . '\',paiement="'.$paiement.'", typePaiement="' . utf8_decode($moyenPaiement) . '" WHERE id_commande=' . $commande->getNum() . '';
$connexion->exec($query);
$query2 = 'UPDATE commande SET mpaiement="' . utf8_decode($moyenPaiement) . '",pxttc="'.$paiement.'" WHERE noCommande=" . $commande->getNum() . "';
$connexion->exec($query2);
For the first one, my $paiement isn't save in my DB. I get a $paiement = 0 while in my second one $paiement is save as I want.
I have the same pattern in my second query $moyenPaiement, moyenPaiement is save as I want but he is not save in my first query.
Sorry for my explanation, it's maybe confused.
You should not combine both single and double quotes, it will be confusing. Try this:
$query = 'UPDATE payee SET payee="oui", datePaiement="' . $datePaiement . '", paiement="'.$paiement.'", typePaiement="' . utf8_decode($moyenPaiement) . '" WHERE id_commande="' . $commande->getNum() . '"';
$connexion->exec($query);
$query2 = 'UPDATE commande SET mpaiement="' . utf8_decode($moyenPaiement) . '", pxttc="'.$paiement.'" WHERE noCommande="' . $commande->getNum() . '"';
$connexion->exec($query2);
Later edit:
Don't forget to print your queries if something weird happens. These queries can be tested in phpMyAdmin too.
print_r($query);