Transform to prepared statement [duplicate] - php

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

Related

mysql order by last value in table separated by comma [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 3 years ago.
so I'll try to be short,
I'm trying to ORDER BY ID from table whose values are separated by commas.
Here's an Image:
I want them to be ordered like this when displayed: 34, 40, 33, 0.
here's my code:
/// movie
$myuserid = $_SESSION['user_id'];
$mymovies = "SELECT p_movies FROM user_details WHERE user_id='$myuserid' ";
$mymoviesresult = mysqli_query($_db,$mymovies);
$mymovie = mysqli_fetch_array($mymoviesresult);
/// movie
$mypurchases = $mymovie['p_movies'];
$sql = "SELECT * FROM movies WHERE find_in_set(id, '$mypurchases') > 0";
$res_data = mysqli_query($_db,$sql);
if($res_data = mysqli_query($_db, $sql)){
if(mysqli_num_rows($res_data) > 0){
while($row = mysqli_fetch_array($res_data)){ include 'movies/appearance.php'; }}}
I tried to add ORDER BY DESC and ASC, it doesn't work. Is it possible to order results in the manner stated above?
Don't know how to explain it better, sorry for my English.
Since FIND_IN_SET() returns the position in the list, you can use that for your ordering.
There's also no need to use two queries, you can join the tables. And you should use a prepared statement to prevent SQL injection.
$stmt = $_db->prepare("
SELECT m.*
FROM movies AS m
JOIN user_details AS d ON FIND_IN_SET(m.id, d.p_movies)
WHERE d.user_id = ?
ORDER BY FIND_IN_SET(m.id, d.p_movies) DESC") or die($_db->error);
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
include 'movies/appearance.php';
}
}

Doing something similar to "mysqli_fetch_array" with Prepared Statements. PHP MYSQL [duplicate]

This question already has answers here:
How to remove the fatal error when fetching an assoc array
(5 answers)
Closed 6 years ago.
I've been trying to get this fixed for the past two days with no luck. I'm switching to prepared statements for security reasons and I'm trying to display reviews. In the recent past, with prepared statements, I could only show one review, although there were many. After trying to figure it out, I switched to the old way (unsafe way) and it worked as it should. This is the code that worked (unsafe way):
$sql = "SELECT rate, title, date, review, recommend, helpful, username FROM rating INNER JOIN users ON rating.user_id = users.id";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$rate = $row["rate"];
$title = $row["title"];
}
}
//Info is displayed :)
$table1 .= '
<li>
<span style="display: inline-flex;" class="stars">'.$rate.'</span><span id="review_title">'.$title.'</span>
</li>
I like having the variables assigned to the row, so I can echo the variables where needed.
Now, trying to get the same result in the prepared statements...that's another story. Here's one of the many attempts that don't work:
$sql = "SELECT rate, title, date, review, recommend, helpful, username FROM rating INNER JOIN users ON rating.user_id = users.id";
$stmt = $db->stmt_init();
if($stmt = $db->prepare($sql)){
if($stmt->execute()){
$result = $stmt->get_result();
$a = $result->fetch_array(MYSQLI_ASSOC);
echo $a;
}else{
echo "Didn't work.";
}
$table1 .= '
<li>
<span style="display: inline-flex;" class="stars">'.$rate.'</span><span id="review_title">'.$title.'</span>
</li>
Does anyone know how I can show all of the reviews (as with the mysqli_fetch_array), but safer with the prepared statements?
I use this way
$stmt = $db->prepare("SELECT name, xp FROM users");
if($stmt->execute()){
$stmt->bind_result($name, $xp);
while($stmt->fetch()){
echo $name . ' has ' . $xp . ' xp.';
}
}else{
echo "Didn't work.";
}

Mysqli query using $_get where a value is missing [duplicate]

This question already has answers here:
Search Form with One or More (Multiple) Parameters
(2 answers)
Closed 6 years ago.
I have a drop-down box where a user can select a location. Then, there is a text box where they can input a maximum rental price (there will be a few more options but to keep things simple just these in the example). Then this will go to a results.php page and using the $_GET array extract the values and query the database
This works fine if both fields are complete, but if they only wanted to search by location and leave the rent field blank it doesn't work and displays results.php?loc=york&rent= in the URL, which then as I have used the AND function displays no results?
I'm very new to PHP and would very much appreciate anyone who can point me in the right direction or what the correct term to search in google for?
<?php
$location = $_GET['loc'];
$rent=$_GET['rent'];
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city &&'$rent'>rent_price ORDER BY ID ASC");
?>
try this
<?php
// you can check for sql injection
$location = $_GET['loc'];
$rent=$_GET['rent'];
// check if $_GET['rent'] is provided and has a value
if( isset( $_GET['rent'] ) && $_GET['rent'] ) {
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' AND rent_price < '$rent' ORDER BY ID ASC" );
// do remaining stuff
} else {
// rent is not provided
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
// do other stuff
}
?>
You can either create 2 queries, or just one with some variables.
$rent = $_GET['rent'];
$rent_options = "";
if(isset($rent)) //add condition
{
$rent_options .= "&& \'rent\'>rent_price";
}
$mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city".$rent_options." ORDER BY ID ASC");
This way, assuming they chose a rent option, it will be added to the query. If not, it will simply be blank space and be ignored.
If the $rent is empty the you have to check it first before querying to database.
if(!empty($rent))
{
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' and rent_price<'$rent' ORDER BY ID ASC");
} else {
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
}

Error: mysqli_fetch_object() expects parameter 1 to be mysqli_result [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 8 months ago.
I don't know what the problem is with this line or how to fix it, before was okay and now I'm getting this error:
mysqli_fetch_object() expects parameter 1 to be mysqli_result
Here is my PHP code:
<?php
}
if($_GET['action']=="user_info")
{
$userid = $_GET['user_id'];
$query = "SELECT * FROM user WHERE user_id ='{$userid}'";
$result = mysqli_query($link, $query);
$user = mysqli_fetch_object($result);
$queryt = "SELECT * FROM user_title WHERE id='".$user->title."'";
$resultt = mysqli_query($link, $queryt);
$rowt = mysqli_fetch_object($resultt);
$title = $rowt->name;
$sorgu = "select * from pub_author where user_id='$userid'";
$publications = mysqli_query($link, $sorgu);
while($a = mysqli_fetch_object($publications))
{
$ids .= $a->pub_id . ',';
}
$ids = rtrim($ids,",");
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids)
GROUP BY YEAR(`year`) order by `year` ";
$publications2 = mysqli_query($link, $sorgu2);
while($a2 = mysqli_fetch_object($publications2))
{
$mount = explode('-', $a2->year);
$accyaz[$mount[0]] = $a2->total;
}
}
?>
As far as your exact error is concerned one of your query is failing, the following steps might help. Ofcourse you question looks duplicate but here are some of the things that addresses your question
Your first query should be like this, with no curly braces, ofcourse untill you have explicitly ids wrapped in curly braces in your table.
SELECT * FROM user WHERE user_id ='$userid'
Secondly you are executing multiple queries so you might wanna consider error checking if your query executes properly or not(because of syntax error columns mismatch table name mismatch many more possibilities): do error checking like this as for while($a...) part
if ($result=mysqli_query($link, $sorgu);)
{
while($a=mysqli_fetch_object($result))
{
$ids .= $a->pub_id . ',';
}
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids) GROUP BY YEAR(`year`) order by `year` ";
//... Your further code
}
else
{
echo "Something went wrong while executing query :: $sorgu";
}
Third i see your are getting pub_id make a comma seperated list of it so that you can give it as a parameter in your last query which is a long shot, why not use sub query for you IN clause like this:
SELECT
COUNT(id) as total, year
FROM publication
where id
IN (
SELECT pub_id FROM pub_author WHERE user_id='$userid'
)
GROUP BY `year`
order by `year`;
The error you are stating translates to this: The query fails somehow, instead of running the mysqli_query($link, $sorgu); line echo $sorgu, go to phpmyadmin and test your query, if it is bad, fix it in phpmyadmin until it works and set it up in the code correctly

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