Currently I am creating a news section for a website.
I have created it so that the news type is separated by a string E.g. category = ,2,4,6,
I don't normally use strings a whole lot, and my initial thought was to do something like this:
$query_listelements = "SELECT * FROM newsitems WHERE released = 1 AND (category = 2 OR category = 4 OR category = 6) ORDER BY date_rel DESC";
Clearly this won't work as I need to isolate / expand the string. so it needs to be something like:
$query_listelements = "SELECT * FROM newsitems WHERE released = 1 AND (category = strval(",2,") OR category = strval(",4,") OR category = strval(",6,")) ORDER BY date_rel DESC";
I don't think the above is the right way to go out things either.
Any thoughts would be really valued!
You may use it like below, sounds better to me.
$category= array ( 2, 4, 6);
$category = implode(',', $category); //Now it is a string like '2,4,6'
$query_listelements = "SELECT * FROM newsitems WHERE released = 1 AND (category IN ($category)) ORDER BY date_rel DESC";
Related
I am trying to get a list of highscores (top 10) of players that played my game.
Everything works except for one thing, the list isn't right.
The first 10 people are correct, but when i go to page 2 the list isn't further going done.
Variables Explain
$gamemode = "Endless"
$filter = "Score"
$startNum = Page1 = 0, Page2 = 10
$maxlimit = 10
Query:
$query = "SELECT ID, Gamemode, Name, Score, ContainersSaved, TimePlayed, Date, ScorePerMinute
FROM $dbName . `highscore`
WHERE Gamemode='$gamemode'
ORDER by `$filter` DESC
LIMIT $startNum, $maxlimit";
Does anyone know what im doing wrong?
If your Score field is varchar try: (or change it to INT)
$order=$filter;
if($filter=='Score') {
$order="ABS($filter);
}
$query = "SELECT ID,Gamemode,Name,Score,ContainersSaved,TimePlayed,Date,ScorePerMinute FROM $dbName . `highscore` WHERE Gamemode='$gamemode' ORDER by $order DESC LIMIT $startNum, $maxlimit";
I fixed it, i forgot to change the 'Score' field from varchar to an INT, so it was trying to Descend on string instead of INT.
Thanks to the tip Imaginaerum gave me :)
I have a page where I want to display articles like the one you're reading (randomly chosen articles from same subcategory). I want to use a php script but the server says I have an error. Here is my script:
$article = mysqli_query($con,"SELECT * FROM sources WHERE ID = '$ID'");
while($row = mysqli_fetch_array($article))
{
code which works perfectly
$samecat = $row['Subcategory'];
}
$samecats = explode(', ', $samecat);
foreach($samecats as $similar){
$scat[] = "Subcategory LIKE %".$similar."%";
}
echo implode(' OR ',$scat);
$samearticle = mysqli_query($con,
"SELECT *
FROM sources
WHERE (".implode(' OR ',$scat).")
AND NOT ID='$ID'
ORDER BY Rand()
LIMIT 0,3 ");
while($row2 = mysqli_fetch_array($samearticle))
{
echo "<a href='article.php?ID=".$row2['ID']."'>» "
.$row2['Headline']."</a>";
}
The connection works perfectly because it works with other components but I have bug here :(((
Any alternative solutions will be fine, but I think this way is better.
error is:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Here is your problem:
https://eval.in/96729
I simulated your code and viewed the sql you're generating. It's like this:
"SELECT *
FROM sources
WHERE (Subcategory LIKE %test% OR Subcategory LIKE %foo% OR Subcategory LIKE %bar% OR Subcategory LIKE %baz%)
AND NOT ID=''
ORDER BY Rand()
LIMIT 0,3 "
You need singlequotes around your terms like:
Subcategory LIKE '%test%'
So you need to:
$scat[] = "Subcategory LIKE '%".$similar."%'";
Really you should enable error reporting for your querying.
Before I show what I have tried, i'll just explain my scenario. I have three tables. Genre, Games, GameGenre.
Genre = The different game genres (Action, Adventure, Multiplayer)
Games = The different games (example 1, example 2, example 3)
GameGenre = the grid and the gaID and also the ggID (genre, game and gamegenreID)
Currently how this works is, firstly you would create a game genre, then add specific games to that genre. So they both have a geID and a gaID.
Now, what I am trying to do is display these according to genre. So that when I choose a genre, only games which have that genre are listed. Hence I have the ggID.
Code:
mysql_query("SELECT * FROM Genre WHERE gaID == geID = '$ggID'");
while($row = mysql_fetch_array($results)){
$geID = $row['geID'];
$gaID = $row['gaID'];
echo statements here.
}
This does not work though, any help please?
Did you tried this ?
mysql_query("SELECT * FROM Genre WHERE gaID = '$ggID' AND geID = '$ggID'");
Try
mysql_query("SELECT * FROM Genre WHERE gaID = geID AND geID = '$ggID'");
SQL is not C++, and = is not an assignment operator, so A = B = C doesn't make sense. And there is not == in SQL.
Namastey!
I'm currently working on one of my projects where I get to one doubt.
What I'm doing is:
I have got 4 tables called:
1: project_degree
2: project_department
3: project_category
4: Projects
project_degree have got four top level degrees which are: B.tech, M.tech, M.C.A. & M.B.A.
project_department have got their respective departments such as: C.S.E, I.T., E.E.E. and so on.
Now, project_category have some categories like PHP, .NET, SAP etc.
What I'm trying to do is, I'm adding a project to database called "projects" where I'm assigning it to its degree, department and category.
Structure of projects table is as follows:
id | project name | degree_id | Dept_id | Cat_id
1 | Sample project | 1 | 3 | 4,3,6,5,9
Now as you can see above, field "cat_id" have got multiple categories where each categories ID have been separated by a comma.
Now when I call a query get all projects from the table called "projects", I want to list of categories related to that particular project and my code goes like this:
$query = mysql_query("SELECT * from projects ORDER BY id DESC");
while($row = mysql_fetch_array($query)) {
$categories = $row['cat_id'];
$cat_arr = explode(',',$categories);
$cat_size = sizeof($cat_arr);
for($i=0;$i<$cat_size;$i++) {
$get_cat = mysql_query("SELECT * from project_category WHERE id='".$cat_arr['$i']."'");
$cat_row = mysql_fetch_array($get_cat);
echo $cat_row['name']; // Here finally I'm getting categories name
}
}
So, finally I'm running nested loop and two queries to get a category name. I doubt it affect the page load time when it comes to huge data.
Is there any better alternative to this situation?
Here should be work
$query = mysql_query("SELECT * from projects ORDER BY id DESC");
while($row = mysql_fetch_array($query)) {
$get_cat = mysql_query("SELECT * from project_category WHERE id IN (" . $row['cat_id'] . ")");
$cat_row = mysql_fetch_array($get_cat);
echo $cat_row['name']; // Here finally I'm getting categories name
}
But normalization is better.
It's better to add a new table, project_has_catID where you can store project.id and cat.id as two columns (project_id and cat_id). Remove the Cat_id column in the project table.
Once done, simply select the name by the next query;
$query = mysql_query("SELECT project_category.name from project_category INNER JOIN project_has_catID phc ON phc.cat_id = project_category.id ORDER BY phc.project_id DESC");
By this, you have a list of category names. You don't have to loop with multiple database communications.
You could load all category names into an associative array first, then look up category names in this array when looping through the projects.
$categoryNames = array();
$query = mysql_query("SELECT id, name FROM project_category");
while ($row = mysql_fetch_array($query))
{
$categoryNames[$row['id']] = $row['name'];
}
$query = mysql_query("SELECT * FROM projects ORDER BY id DESC");
while ($row = mysql_fetch_array($query))
{
$categoryIds = explode(',', $row['cat_id']);
foreach ($categoryIds as $cat_id)
{
$cat_name = $categoryNames[$cat_id];
//do what you want with the name here
}
}
This way, you don't have to change your database structure, or the structure of your code. And you only have to execute two queries in total, so this is by far the simplest solution.
Needless to say, normalization is always better as others have indicated (never use a column that contains multiple comma-separated values), but you probably knew that and had your reasons for setting up your database tables this way.
I am having a small trouble retrieving results that I hope someone can help me with.
I have a field called $incategory which is a comma based string, and what I want to do is explode the into an array that can be used to retrieve results as below (Hope that makes sense):
<?php
$showlist = $row_listelements['incategory'];
// ** e.g. $incategory = 1,3,5,
// ** What I want to do is look at table 'category'
// ** and retrieve results with an 'id' of either 1, 3 or 5
// ** Display Results
mysql_select_db($database_db, $db);
$query_display = "SELECT * FROM category WHERE id = ".$showlist." ORDER BY name ASC";
$display = mysql_query($query_display, $db) or die(mysql_error());
$row_display = mysql_fetch_assoc($display);
$totalRows_display = mysql_num_rows($display);
?>
You can use the IN keyword of SQL directly like this.
query_display = "SELECT * FROM category WHERE id IN (".$showlist.") ORDER BY name ASC";
Another tip would be to stop using MYSQL_QUERY as it is deprecated in PHP 5.3
Edit: If $showlist = '1,3,5,' you will need to remove the last comma from the string to make it useable in the query. Just use this query then
query_display = "SELECT * FROM category WHERE id IN ('".str_replace(",", "','", substr($showlist, -1))."') ORDER BY name ASC";
Use explode function and use , as delimiter.
refer here http://www.w3schools.com/php/func_string_explode.asp
Hope this helps.
First, you have explode the $incategory string into an array containing all of the category number. For example:
$incategory = explode(",", $incategory);
And then you just have to execute this query:
$query_display = "SELECT * FROM category WHERE id = "
. $incategory[$i] . " ORDER BY name ASC";
The $i should be defined beforehand (usually using loop).