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';
}
}
Related
$category = htmlspecialchars($_GET['category']);
$sql = "(SELECT number
FROM german
WHERE german.category_german LIKE ".$category."
ORDER BY number DESC
LIMIT 1) as 'high',
(SELECT number
FROM german
WHERE german.category_german LIKE ".$category."
ORDER BY number ASC
LIMIT 1) as 'low'";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$high_value = $row[high];
$low_value = $row[low];
$r_n = rand($low_value,$high_value).PHP_EOL;
echo $r_n;
}
}
What am I missing? I want the highest and the lowest value of a table, why can't I save that value in PHP? I just can't access the values. And I tried out MIN and MAX as well, but they didn't function neither:
$category = htmlspecialchars($_GET['category']);
$sql = "SELECT MIN('number') AS 'low', MAX('number') AS 'high' FROM german WHERE german.category_german LIKE ".$category."";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$high_value = $row[high];
$low_value = $row[low];
$r_n = rand($low_value,$high_value).PHP_EOL;
echo $r_n;
}
}
As a result of $r_n I only get 0. The database shouldn't be the problem. Beforehand (where I only used the highest value) everything functioned:
$category = htmlspecialchars($_GET['category']);
$sql = "SELECT number FROM german WHERE german.category_german LIKE ".$category." ORDER BY number DESC LIMIT 1";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$r_n = $row[0];
$r_n = rand(1,$r_n).PHP_EOL;
echo $r_n;
}
}
You can't use multiple SELECT statements at top-level of a query. They would have to be subqueries:
SELECT (SELECT ...) AS high, (SELECT ...) AS low
Your second query would have worked, but you shouldn't have quotes around number. That makes it a literal string, not the column values. So MAX('number') should be MAX(number), MIN('number') should be MIN(number). See When to use single quotes, double quotes, and backticks in MySQL
And if category is a string, you need to put quotes around $category:
WHERE german.category_german LIKE '".$category."'"
But the better way to resolve that problem is to use a prepared statement with parameters, How can I prevent SQL injection in PHP? than substituting variables directly into the query. See
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']
]
);
This question already has answers here:
selecting unique values from a column
(9 answers)
Closed 6 months ago.
I have a database with multiple entries. One specific column of entries I am interested in is called sample_group. If there are 10 rows of entries in sample_group, I am trying to create a array of the unique entries using PHP.
For example, the entries would be "food", "food", "water", "food", "swabs", "swabs", "swabs", "food", "water", "water"and after creating an array should be: array("food", "water", "swabs").
Here is my attempted code, it sort of works but the array has an empty entry at the end:
$sql3 = "SELECT * FROM samples_database WHERE order_id=$order_id;";
$result3 = mysqli_query($conn, $sql3);
$group_array = '';
while ($input = mysqli_fetch_array($result3)) {
$group_array .= $input['sample_group'] . ',';
}
$group_array2 = array_filter(array_unique(explode(',', $group_array)));
And then the foreach loop:
foreach ($group_array2 as $group) {
//do something
}
Can anybody please push me in the right direction?
It would be much simpler if you made $group_array an actual array:
$group_array = array();
while ($input = mysqli_fetch_array($result3)) {
$group_array[] = $input['sample_group'];
}
$group_array = array_unique($group_array);
foreach ($group_array as $group) {
//do something
}
I would suggest just doing a SELECT DISTINCT on the MySQL side:
$sql = "SELECT DISTINCT sample_group FROM samples_database WHERE order_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$group_array[] = $row['sample_group'];
}
}
Note: You should ideally use a prepared statement when building your SQL query, and avoid concatenation. I have attempted to provide code which uses a prepared statement.
Also, I replaced your SELECT * (all columns) with just SELECT sample_group. The reason for this is that for one thing, selecting all columns when your script only needs one of them wastes network bandwidth, and might hurt performance. Another reason is that SELECT * makes it ambiguous about which columns your script really needs to use.
This question already has answers here:
Display single column value of mysqli query
(3 answers)
Closed 6 years ago.
Here is my query:
$qry1 = "SELECT COUNT('name') FROM `brands` WHERE `catagory_id` = '".$id."';";
$res = mysqli_query($conn, $qry1);
I want the value of count and want to use it in another query. How is that possible?
Two steps:
1. give a meaningful name to the value calculated by count(name), total e.g.
2. fetch first row of the result and access value from 1 using the name total
$qry1 = "SELECT COUNT(name) as total FROM `brands` WHERE `catagory_id` = '".$id."';";
$count = $mysqli->query($conn, $qry1)->fetch_object()->total;
Try;
$qry1 = "SELECT COUNT(name) as counts FROM brands WHERE catagory_id = '".$id."';";
$res = mysqli_query($conn, $qry1);
$row = mysqli_fetch_array($res);
$count = $row["counts"];
now this $count variable holds the value. You may include this variable in other query.
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