Php and MySQL Querys using values in other tables - php

So i'm trying to fetch all of the user_id's from the users-events table where the event_id is equal to the passed in variable (let's say it's 2 for now.)
In the database there are currently 2 ID's registered to that event_id which are 1 and 2.
This code however only returns the first of these values. I feel like i need to incorporate the first query into the while loop but i dont know how to go about it.
Any help would be greatly appriciated!
function showregisteredplayers($id){
$eventq = mysql_fetch_assoc(mysql_query("SELECT user_id FROM `users-events` WHERE event_id = '".$id."'"));
$rosterq = mysql_query("SELECT username FROM `users` WHERE `user_id` = '".$eventq['user_id']."'");
while($player = mysql_fetch_assoc($rosterq)){
echo("
<tr>
<td>".$player['username']."</td>
</tr>
");
}
}

Use a sub query then kill your first one.
SELECT username FROM `users` WHERE `user_id` IN
(
SELECT user_id FROM `users-events` WHERE event_id = 5
)
Rest is fine, you already are looping over the second result set so this should do. Unless you have a large number of records, there should not be any considerable performance degradation with the use of IN otherwise you can optimize the query.
5 is obviously just an example, use $id there correctly.

Why not use a JOIN?
SELECT username
FROM `users` AS u
INNER JOIN `users-events` AS ue ON u.user_id = ue.user_id
WHERE event_id = ?
Several advices:
Don't use mysql_ functions because are deprecated
Use prepared queries, then you only need to loop through execute method, take a look to Example 3 in this link (example from php.net using mysqli)

Related

Is there a more eloquent way of doing these MySQL queries?

I'm making 4 individual queries to a MySQL DB, all of which are identical except the WHERE parameters. 2 of which are:
$totalInvites = mysqli_num_rows(mysqli_query($con, "SELECT code FROM invites"));
$usedInvites = mysqli_num_rows(mysqli_query($con, "SELECT code FROM invites WHERE used IS NOT NULL"));
Is there a way of doing the $totalInvites query and from the returned table, do the WHERE call without doing another query?
If that's confusing, this is an example of what I mean:
$query = mysqli_query($con, "SELECT code FROM invites");
$totalInvites = mysqli_num_rows($query);
$usedInvites = mysqli_num_rows($query /*WHERE used IS NOT NULL*/);
I know that's not proper syntax but that's what I was trying say.
If you just want counts then retrieving the entire database and throwing out the results is not really a good idea. Instead jus task for a count:
SELECT COUNT(*) AS count, used
GROUP BY used
This will give you up to two rows, one count for those that are used and one that isn't presuming used has only NULL or a single non-null value.
Use as little SQL as possible:
SELECT if(used is null, 0, 1) AS used, code
FROM invites
And parse result in PHP according to what you need
SELECT
(SELECT code FROM invites) total
(SELECT code FROM invites WHERE used IS NOT NULL) used

How do I use 2 WHERE clauses including two tables wherein a column in a Query

I try to use different columns within different tables.
Like I want it to run the query If or Where [table.column]
users.username = 'ExampleUsername' AND users.cardnumber = ''
I don't think I can use NULL instead of '', because its an empty text string?
users.cardnumber = NULL
Anyways, I couldn't come further as this:
INSERT INTO users (cardnumber, hasone)
WHERE users.username = 'ExampleName' AND users.cardnumber = ''
SELECT number, sethasone
FROM cards
WHERE cards.used = '0'
LIMIT 1
I'm a bit of new with SQL, but after I got it right I could put the code into my php script.
-
SOLVED! :
I've used two queries for each column.
update users
set hasone=(select sethasone from cards where used='0' LIMIT 1)
where username='TestUser'
and
update users
set cardnumber=(select number from cards where used='0' LIMIT 1)
where username='TestUser'
then I just deleted the row from cards and I was done.
delete from cards
where used = '1'
LIMIT 1
I gave the user a cardnumber from the table cards and delete that row in cards.
I think you are trying to write a nested query but you didn't know how to write it. If you want to write select query within insert or update query so before doing this Click here to read about sub-query or nested query.
Well, I think that you're trying to re-create a JOIN between 2 table. What you need to do is to add a "card_id" field into the users table. Then to get the user AND the card you can do something like :
SELECT * FROM users u LEFT JOIN cards c ON c.id = u.card_id

Problems with querying when a value is null

I am using php to query a database for one piece of information from each of 10 separate tables currently. The problem with using multiple queries is that it is extremely slow when accessing the web page that uses all of this information. I cannot seem to get all of the information back that I am wanting when one of the values does not exist due to the WHERE... statement.
For instance, my single queries are all in this format:
SELECT eval_id FROM eval WHERE user_id = $id;
My multiple table query looks like this:
SELECT eval_id,list_id,tab_id
FROM eval,list,tab
WHERE eval.user_id = $id
AND list.user_id = $id
AND tab.user_id = $id;
I tried to combine these queries into one large query, but when the user_id of one does not exist in the table, the comparison in the WHERE... statement screws up the entire query. Does anyone know the best way to retrieve all of this information?
Assume that the tables are "eval, list, and tab," and their id's are *_id respectively. What would be the best way to query this even if eval does not contain a result where the user_id = $id?
SELECT eval.eval_id, list.list_id
FROM user
JOIN eval ON eval.user_id = user.id
JOIN list ON list.user_id = user.id
WHERE user.id = $id
Hope it can help you.
Update: Just think about other solution:
SELECT eval_id as id, "eval" as table
FROM eval WHERE eval.user_id = $id
UNION
SELECT list_id as id, "list" as table
FROM list WHERE list.user_id = $id
You could use either of the following to your query in the WHERE statement:
AND TABLE.TABLE_id <> null //null
AND TABLE.TABLE_id <> 'null' //String null
AND TABLE.TABLE_id <> '' //empty String
Check your database to see what kind of empty value your id is returning and choose the addition that matches it.
Also, while LEFT JOINs may be better looking in a query, they are not always faster so make sure you test it before using.

This query on mysql is taking forever to execute

im making a simple admin module to query the database to show the results. Im using this query via php:
SELECT
*
FROM myTable
WHERE id in(SELECT
id_registro
FROM myOtherTable
where id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
)
order by id DESC
The result shows, however, it takes very long like 2 minutes..Anyone can help me out?
Thanks!
Without seeing your database, it is hard to find a way to make it faster.
Maybe you can try to turn your WHERE IN to INNER JOIN. To something like this
SELECT * FROM myTable INNER JOIN myOtherTable
ON (myTable.id = myOtherTable.id_registro)
WHERE myOtherTable.id_forma = '$id_club'
AND myOtherTable.fecha_visita LIKE '%$hoy%'
ORDER BY myTable.id DESC
Noted that you should sanitize your variable before putting it SQL query or using PDO prepare statement.
Sub Queries takes always time, so its better to ignore them as much as possible.
Try to optimize your query by checking its cardinality,possible keys getting implemented by DESC or EXPLAIN , and if necessary use FORCE INDEX over possible keys.
and I guess you can modify your query as:
SELECT
*
FROM myTable
inner join id_registro
on (id = id_forma )
where
id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
order by id DESC
LIKE in mysql may take a long time ,with or without index.
Do u have a very large DB?

how to properly use Mysql to SELECT * FROM table WHERE column='Any_value_in_Array'

Okay so I'm basically a noob when it comes to setting up tables and querying them ... but I think My title explains what I'm trying to do pretty well and I believe I'm looking for a way to use a JOIN but for the life of me can't figure out exactly how to do it (I've read some examples on S.O. and tutorials around the web but haven't been able to wrap my head around it). Basically I have a table called userFollowsSeries which has three columns
| userID | seriesID | series_title |
------------------------------------
| int | int | var_char |
and another table series that has a primary key seriesID and a bunch of relevant information about the series. Now I want to get all Information in table series for each seriesID for a user.
Now I'm basically trying to get each seriesID based on a single userID like this
$userFollows = mysqli_query($con, "SELECT * FROM userFollowsSeries WHERE userID='$user_id'") or die(mysql_error());
while($follows = mysqli_fetch_array($userFollows)){
$show_id=$follows['seriesID'];
echo $show_id; //this is realy just here for testing
$result = mysqli_query($con, "SELECT * FROM series WHERE id='$show_id'") or die(mysql_error());
while($row = mysqli_fetch_array($result)){
// i get and print out everything in a formatted for my html code
}
}
now I realize that this is less then ideal and is not very efficient but can't figure out how to do all of this in one statement/query using again i presume some sort of JOIN statement. Everything I have Works but is just really slow (presumably because of the query embeded in the while loop). Anyway's you can help me out with how a join or new table structure to improve this would be awesome and greatly appreciated.
Something along the lines of SELECT * FROM `series` WHERE `id` IN (SELECT `SeriesID` FROM `userFollowsSeries` WHERE `userID`=$user_id) should work nicely. Just be aware that it may not make good use of indexes. It may be better to select the IDs, build an array of them, then use IN with implode to join the array.
A JOIN basically glues two tables together on a column. Take this as an example:
SELECT * FROM userFollowsSeries INNER JOIN series ON (userFollowsSeries.seriesID = series.seriesID)
What we're doing here is, in effect, selecting everything from the userFollowsSeries, then for each record, attaching the row from the series table which satisfies the condition in the ON clause.
Your query should be
SELECT s.*
FROM userFollowsSeries ufs
INNER JOIN series s
ON s.id = ufs.seriesID
WHERE ufs.userID = {$user_id}
and you should make a foreign key or an index on field seriesID of table userFollowsSeries.

Categories