PHP - search on query [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I want to select query from database. if I write this code :
$selectOption = $_GET['name'];
echo $selectOption.'<br>';
$sql = "SELECT 'rpm' FROM sn WHERE power = '1s1s'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "rpm: " . $row["rpm"];
}
} else {
echo "0 results";
}
It shows me correct answer. Otherwise , if I write this :
$sql = "SELECT 'rpm' FROM 'sn' WHERE 'power' = '$selectOption'";
It shows me 0 results. any suggestion to correct above query?

You need to do two things, both are stated in comments:-
1.Use backticks(`) in your query like this:-
$sql = "SELECT `rpm` FROM `sn` WHERE `power` = '$selectOption'";
2.Prevent your query from SQL Injection. For that use prepared statement. Link is given in comment section. For your help i put it in my answer :- How can I prevent SQL injection in PHP?

Related

Transform to prepared statement [duplicate]

This question already has answers here:
How to use mysqli prepared statements?
(3 answers)
Closed 2 years ago.
This is the current PHP script I am using:
$query = "SELECT * FROM tbl WHERE status='Godkjent' AND team='{$_SESSION['team']}' ORDER BY date DESC LIMIT 5";
if ($result = $link->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
echo "{$row['pp']}";
// determine if user has already liked this post
$results = mysqli_query($link, "SELECT * FROM kudos WHERE sale_id='{$row['id']}' AND ident_id='{$_SESSION["ident"]}'");
$resultSet = $link->query("SELECT kudos.sale_id as TheID, kudos.ident_id AS TheIdent from kudos,tbl where kudos.sale_id = '{$row['id']}' AND tbl.id = kudos.sale_id");
if (mysqli_num_rows($results) == 0 ) { // Not liked
echo "<a style='color:#FFFFFF' class='btn' href='kudos.php?id={$row['id']}'> 🔥 $resultSet->num_rows </a>"; // Gonna remove this
} else { // Has liked
echo "<b style='color:#FFFFFF' class='btn'> 🔥 $resultSet->num_rows </b>"; // Gonna remove this
}
}
/*freeresultset*/
$result->free();
}
Shortly explained the results and resultSet query: Check if current user has liked post. Display total number of likes for each 5 posts. Do not like user like post again if already liked.
So I am query'ing the last 5 rows from tbl table. And inside that query, I have another query that selects all the values from kudos table where sale_id is equal to the first query's row ID. I know the solution I am using now is NOT safe agains SQL Injections, so I am trying to look into prepared statements. Can someone help me transform these questions to prepared statements?
There's a really simple library you can use that uses prepared statements called Simple PDO.
Using that, you would do something like this:
$results = $db->select("SELECT * FROM tbl
WHERE status = :status
AND team = :team
ORDER BY date DESC LIMIT 5", [
'status' => 'Godkjent',
'team' => $_SESSION['team']
]
);

MySQL Select statement not functioning if there are alphabetic characters [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
Expected result:
Loop through all entries in the checkedout table, and select the entry from the game table where the barcode field is the same.
Actual behaviour / issue:
For the most part, this is working as intended. If I set the barcode field to a numerical value in the game table, and then "checkout" that barcode, everything works as intended. The barcodes I'll be using are in the format of ABC12345678. Once I change the values in the barcode field, in the game table to the alphanumeric version, it no longer runs the secondary select statement and displays this error: Fatal error: Call to a member function fetch_assoc() on boolean which refers to the following line: while ($row2 = $result2->fetch_assoc()) {
Oddly enough, if I run the exact same select statement SELECT * FROM game WHERE barcode = 'ABC12345678' on the MySQL instance, it returns the proper results.
Question
Do I need to be using a different method to select based on the value now being alphanumeric? Do I need to manipulate the data in some way?
Code:
$sql = "SELECT * FROM checkedout";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userid = $row["userid"];
$barcode = $row["barcode"];
echo "$userid </br>";
echo "$barcode </br>";
$sql2 = "SELECT * FROM game WHERE barcode = " . $barcode . "";
$result2 = $conn->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$title = $row2["title"];
$console = $row2["console"];
echo "$title </br>";
echo "$console </br>";
}
checkedout table:
game table:

MySql SUM not returning any results [duplicate]

This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 1 year ago.
I'm trying to get the sum off all the prize money from a column in a MySql table, but I'm not getting a result.
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
while ($rows = mysqli_fetch_array($result)) {
echo $rows['SUM(prize_money)'];
}
I just want to add all of the numbers in the prize_money column then echo the results.
Thank You
You should apply an alias to the SUM so it is easier to access in the PHP.
You then need to pass the connection string to the mysqli_query function as the first parameter.
So for example if your database connection were:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
then you'd use this code to execute the query and assign the alias:
$result = mysqli_query($con, 'SELECT SUM(prize_money) AS sum_prize_money FROM cards');
$row = mysqli_fetch_assoc($result);
$sum = $row['sum_prize_money'];
echo $sum;
Do you get a result if you do this:
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
$rows = mysqli_fetch_array($result);
echo $rows
As good practice, you should learn to aliase your sql variables e.g. SUM(prize_money) AS total etc

PhP MySQL "WHERE" query returns null / is empty [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Ok, hi. So i was trying to create an Android App wich uses a MySQL database to generate a RecylerView. To get the Data i use a PhP file store on the same Server. But i wanted to extend the App a bit. And now if i call this Line: $query = 'SELECT * FROM items WHERE catid = "$catid"'; the result is empty.
The weird Thing is: If i enter the Query in PhPMyAdmin it shows me the correct Results.
Here is the Complete PHP-File (Database Login removed) (Annnd the mandatory disclaimer: I'm not fluent in English, so please excuse some typos c:)
EDIT: I think some People missunderstood: The Problem is not in Android.. I'm sure. And the "generate".. just ignore that i didnt know what other Word i could use.. So the Problem is only in the PHP File
<?php
$connection = mysqli_connect("","","","");
$type = $_GET["t"];
if($type == "categorys"){
$query = "SELECT * FROM categorys";
}else{
$catid = $_GET["id"];
$query = 'SELECT * FROM items WHERE catid = "$catid"';
}
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
?>
Write it like this, with double-quotes:
$query = "SELECT * FROM items WHERE catid = $catid";
If catid is a string, then:
$query = "SELECT * FROM items WHERE catid = '$catid'";
Anyway, you should use prepared statement.
Try this:
$query = "SELECT * FROM items WHERE catid = '$catid'";
or:
$query = "SELECT * FROM items WHERE catid = '".$catid."'";

Why the mysql query is not evaluated properly? [duplicate]

This question already has answers here:
why this mysql query is not working?
(7 answers)
Closed 8 years ago.
Please help me regarding the specified problem:
The code section:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where
id='$_GET[id]' ORDER BY eventdate");
// the above query is not working
if (! $result) {
echo mysql_errno() . ": " . mysql_error(). "\n";
}
if ( mysql_num_rows($result) == 0 ) {
print "<p>No events right now.</p>\n";
}
else {
$lasteventmonth = '';
while ($row = mysql_fetch_array($result)) {
$eventmonth="";
$eventmonth = date("F Y",$row['eventdate']);
if ($lasteventmonth != $eventmonth) {
print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
}
$lasteventmonth = $eventmonth;
showEvent($row);
}
}
?>
........................
........................//other codes
when the code evaluates as follows:
No events right now.
But specific id is present in the database and if $_GET['id'] is echoed in the page the value is shown.
what is id in id='$_GET[id]' at the beginning?
If you have a query http:// ... ?id=123, I would put id in quotes. Having said that, better like this:
$id = mysql_real_escape_string($_GET['id']); // safe against SQL injection
$sql = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate, UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where id='$id' ORDER BY eventdate";
$result = mysql_query($sql);
If you are still getting trouble, use echo to check the variables $id and $result before the query runs; then you will have a clearer idea why it is not running the query you expect.
I am sure id=$_GET[id] is checking an int versus an int where you have it checking an int vs a string. Remove the single quotes around $_GET['id'] and try again. The single quotes define it as a string rather than an int.

Categories