SELECT * FROM table WHERE (value in cell as array) = $searchid [duplicate] - php

This question already has answers here:
How to regex in a MySQL query
(2 answers)
Closed 8 years ago.
I've got a db_table where some cells contain comma separated arrays to link them to all the corresponding rows in a different table column, like [846,1400,1657].
So how do i select all rows where that cell has one matching value in the array?
$result = "";
$searchid = $_POST['id'];
$query = mysql_query("SELECT * FROM Company WHERE City/*<-the array*/ LIKE '%$searchid%'");
$count = mysql_num_rows($query);
if($count == 0){
$result .= "no companies";
} else {
while($row = mysql_fetch_array($query)){
$name = $row['Name'];
$result .= "<div class=\"result\">$name </div>";
}
}
echo $result;
This gives all companies with $searchid, but if $searchid = 25, it will return the ones with 25 in that column as well as those with for example 250 and 725. :/
Without the wildcards tho:
$query = mysql_query("SELECT * FROM Company WHERE City/*<-the array*/ = '$searchid'");
will return the rows with only $searchid in that cell, for example if $searchid = 25 a cell with [25] and not one with [25,456] or [12,13,25]
I've goggled for 48 hours and tried everything i found, think this should be an easy one to crack.
What have i missed???

The FIND_IN_SET function might work for this one. Here's an example:
SELECT * FROM Company WHERE FIND_IN_SET('25', City) > 0
The example assumes that the City column is the one with the comma-separated list; I think that's what your question states.

You could try using the like statement :
SELECT * FROM Company WHERE City LIKE "%25%";
Obviously this would select ones with 250 in too but it's a start.

You can't do split in mysql, you should have used a transitional table :
city_company
------------
id_city
id_company
Where you could have stored all these relations.
Though you could use like for a quick dirty hack.
Here is how you could do it :
$query = mysql_query("SELECT * FROM Company WHERE concat(',',City,',') LIKE '%,$searchid,%'");

Related

How to return only items that occur in 2 sql select statemnts

I have two different sql statements. $sql grabs all the items whose title matches a certain search text. $cat_sql grabs all the category_items that are in a certain category. An item has an ID. A category_item has a field called item_id which is a foreign key to IDs in the items table
...
mysqli setup code
...
$title = $_POST["title"];
$cat_id = $_POST["cat_id"];
$cat_sql = "SELECT * FROM category_items WHERE category_id = '".$cat_id."'";
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' Limit 70";
if (!$result_cat = $mysqli->query($cat_sql)) {
// The query failed.
echo "<h2 >ERROR</h2>";
exit;
}
if (!$result = $mysqli->query($sql)) {
// The query failed.
echo "<h2 >ERROR</h2>";
exit;
}
Then I display all items:
while ($item = $result->fetch_assoc()) {
include 'item_card.php';
}
Currently this just displays all items fetched in the $sql query. Is there some way to remove all items from $result that do not have their ID represented as an item_id in $result_cat?
NOTE:
I would strongly prefer not to do just combine both SELECT statements into a table join because the actual $sql and $cat_sql are not nearly as simple as I have represented here. Also, they vary depending on which if statement they are in.
My question is: given $result and $result_cat, can I remove items from $result?
EDIT 1
As suggested by comments I am making an array if item_ids then doing an in_array query. Progress thus far:
$result_cat_ids = [];
while ($cat_item = $result_cat->fetch_assoc()) {
$result_cat_ids[] = $cat_item['item_id'];
}
EDIT 2 Here is the working code following the suggestions in the comments
if (in_array($item['id'], $result_cat_ids)) {
include 'item_card.php';
}
You may also use 'INTERSECT' sql clause.
$sql = "SELECT * FROM items WHERE id IN (SELECT item_id FROM category_items WHERE category_id = '".$cat_id."' INTERSECT SELECT id FROM items where title LIKE '%". $title ."%')";
This way, you can query for items that accomplish both conditions.
Note: I'm not using "limit 70" but you may add it as well.

PHP - position in table

How can I find the position a certain row has in my database table?
In my database I have a bunch of Players from a game. They have columns such as ID, name, level, world, and so on.
I want to sort them by Level, and see what position they are in in the list.
So far I've tried this, but it only prints out 0 (the start value I put). It does not seem to iterate through.
Previously I made sure the name is stored in $name.
$query = "SELECT * FROM rookstayers ORDER BY level DESC";
$globalPos = 0;
$result = mysql_query($query);
$num = mysql_numrows($result);
$i = 0;
while($i < $num) {
$posName = mysql_result($result, $i, 'name');
if($posName == '$name')
{
$globalPos = $i;
break;
}
$i++;
}
If my table looks like this (after sorting it by level):
name - level
Joe - 50
Jacob - 47
Sarah - 34
Anna - 19
Then "Sarah" would be number 3.
Anna number 4, etc...
I want the position-number to be in $globalPos.
I only found pure SQL code for this, but I want it in PHP. Is it not possible to do in PHP?
I'm not sure if this is the only problem:
If you use single quotes ', the string is not parsed for variables. If you want to compare a string stored in $name with a string stored in $posName, you should use $posName === $name. You could also use $posName === "$name", but the double quotes are unnecessary.
Notice also, that the mysql functions are deprecated. You should use mysqli or PDO_MySQL instead. (See Choosing an API)
<?php
/*
CREATE TABLE results
(name VARCHAR(12) NOT NULL PRIMARY KEY
,score INT NOT NULL
);
INSERT INTO results VALUES
('Anna',19),
('Jacob',47),
('Joe',50),
('Sarah',34);
*/
include('path/to/connection/stateme.nts');
$query = "
SELECT name, score FROM results ORDER BY score DESC;
";
$result = mysqli_query($conn,$query);
$i=1;
while($row = mysqli_fetch_assoc($result)){
echo $i." ".$row['name']." ".$row['score']."<br/>\n";
$i++;
};
?>

How to find total rows before required row [duplicate]

This question already has answers here:
Rank function in MySQL
(13 answers)
Closed 8 years ago.
I have a text based mafia game and I am selected some GameRecords. The game records are all defined in the "users" table. For this example I am using "totalcrimes". I need to select all the rows from the users table and order it by totalcrimes and then find out which row each specific user is that is viewing the page.
If I was the user that was "ranked" 30th it would echo "30". The code I use to find the top 5 is here however I need to expand on it:
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes)){
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
echo "
<tr>
<td bgcolor='#111111' width='5%'>$i</td>
<td bgcolor='#111111' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='#333333' width='45%'>$TotalCrimes</a></td></td>
</tr>
";
}
?>
I am going to assume that you already have a variable set to hold the current users ID number and total crimes, so in this case I will use $user as my variable.
Change yours to fit.
Now, I see 2 instances in which you could mean as your post wasn't very specific, so I will address both.
To show the number at the top of the page, you would use something like;
<?php
$sql = "SELECT * FROM `players` WHERE `totalcrimes` > '{$user['totalcrimes']}'";
$run = mysql_query($sql);
$rank = mysql_num_rows($run) + 1;
echo 'Your rank: ' . $rank;
Other than that, I see it's possibly being used to highlight your row, so something like this would suffice;
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes))
{
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
$primary = '#111111';
$secondary = '#333333';
if ($Row['id'] == $user['id'])
{
$primary = '#222222';
$secondary = '#444444';
}
echo "<tr>
<td bgcolor='$primary' width='5%'>$i</td>
<td bgcolor='$primary' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='$secondary' width='45%'>$TotalCrimes</a></td></td>
</tr>";
}
If neither of those give your requirements, please comment and I'll edit to suit.
edit: I've worked on games for a few years - care to share the link to yours?
This can do the trick
SELECT COUNT(*)+1 as rank
FROM users
WHERE totalcrimes > (SELECT totalcrimes
FROM users
WHERE user_id='12345' AND status='Alive' AND robot='0');
So it counts all rows with greater totalcrimes than selected user (in this example I have used user_id column and some id 12345), than adds 1 on that sum and returns as rank value.
Course, modify WHERE clause inside the brackets to make it work for you.
I assumed that table name is users and user's id is integer user_id.
Test preview (Navicat Premium):
What this query does? It returns number of selected rows + 1 as rank column, from the table users where totalcrimes is greater than totalcrimes of some user. That user's totalcrimes is selected by another query (by its user_id). If you have multiple users with same totalcrimes value, this query will return same rank for all of them.

PHP Pagination-related MySQL query issue

I'm trying to do 2 things.
1) Get the amount of rows in this query
SELECT
COUNT(*)
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
As you can see that is no problem ^^
2) Determine the number within the range of rows that is returned by id
Ex: ID 765 is Item 4 of 7 where column_1 = 152 and column_3 = 42
Does anyone have any basic solutions to this problem with almost pure MySQL? I'd like to avoid iterating through all the rows and setup a counter to increment until it matches current id like this:
$sql = '
SELECT
*
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
';
$query = mysqli_query($sql);
$current_id = 2523;
$i = 1;
while ($row = mysqli_fetch_assoc($query)) {
if ($row['id'] == $current_id) {
$current_position = $i;
}
$i++;
}
print 'Current position in range is: '. $current_position;
Also please don't worry about the actual syntax, I won't be using this exact script, but you get the logic that I'd like to avoid using. If anyone has a better solution, please let me know. Thanks in advance!!

Total up how many men and how many women in a column. Possibly in order to repopulate the planet

Trying to search through a column in a db, and pull out the total number of males, and total number of females.
This data is stored in the db as f and m in the whatsex column.
$query = "SELECT whatsex, COUNT(*) FROM soberdata GROUP BY whatsex";
$result = mysqli_query($connection,$query) or die(mysql_error());
$sexdb = mysqli_fetch_array($result);
$totalmale = $sexdb['m'];
$totalfemale = $sexdb['f'];
echo $totalfemale." & ".$totalmale;
This code outputs nothing. What am I doing wrong?
$sexdb have only "whatsex" and "COUNT(*)" columns. You should use one of them
try
print_r($sexdb);
and look if some of results meet your needs
Your query is going to return a whatsex value, and a COUNT(*) value, not m or f. Doing a var_dump($sexdb) would show you what's in the array.
You are treating a multi-dimensional array as flat. You could do this to flatten it
$query = "SELECT whatsex, COUNT(*) as total FROM soberdata GROUP BY whatsex";
while ($row = mysqli_fetch_array($result)) {
$$row['whatsex'] = $row['total']; // this makes a variable ($m or $f) using the value of the row
}
$totalmale = !empty($m) ? $m : 0;
$totalfemale = !empty($f) ? $f : 0;
You should empty check the results of the db in case there is no male or female entries to avoid errors.

Categories