Need help sql "LIKE" operator - php

Users on my site get to add their friends. The way i am trying to do it is when they add a new friend It updates the "friends" column so.. if the user "bobby" had friends named tom and Joe already and they want to add another friend "bob" it will update the column so it would now look like " tom, joe, bob, ect.." so.. my issue is each one of these friends has data in a table called items with their information age, city etc.. when bobby hits the button "show()" I need it to retrieve each friend that is in "bobby's" friend column with their info. So this is where I am at.
$show = mysql_query("SELECT `friends` FROM `Friends` WHERE`Username`='".$_SESSION['Username']."' ") or die(mysql_error());
$showw = mysql_fetch_object($show) or die(mysql_error());
$yup = mysql_query("SELECT * FROM `items` WHERE Username LIKE '%".($showw->friends)."%' ") or die(mysql_error());
It won't return any data because i can't figure out a way for it to sort through then names. Can I tell it to get each name after each comma?

First off, you should have a separate table to map the friends to a particular user. You will face a lot of complications if you continue it the way you have now.
Anyway, even though this is not recommended, in your case,
$show = mysql_query("SELECT `friends` FROM `Friends` WHERE`Username`='".$_SESSION['Username']."' ") or die(mysql_error());
$showw = mysql_fetch_object($show) or die(mysql_error());
$friends = "'" . str_replace(", ", "', '", $showw->friends) . "'";
$yup = mysql_query("SELECT * FROM `items` WHERE Username IN (". $friends .") ") or die(mysql_error());
IN will filter match all the comma separated values.
PS: Please consider using PDO or any other database library as mysql_* functions are getting deprecated over the next release :)

Related

MySQL selecting from two tables in the same query

I am trying to select everything from two different mysql tables. I imploded an array called friends so that I can select everything about the user's friends from both tables. Originally I wanted to perform one query on one table and then in a while loop a query on the other. But that didn't work. If you know I way I can nest while loops then please be sure to comment/answer this question.
Here's my code:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
echo '<br><br>';
}
Note: $row['last_name'] is from the users table and $row['body'] is from the text_post table. I am receiving this error whenever I run my code Column 'username' in where clause is ambiguous
Please help me.
UPDATE:
I changed my query to: $sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con)); but now it echo's every match twice:
parker hello
parker hello
simms what is up
simms what is up
simms it's raining
simms it's raining
jorge potato
jorge potato
Why is it doing that?
The only thing that is the same in both tables is the username.
Thanks for your question. The issue here is the error that you are receiving of:
Column 'username' in where clause is ambiguous.
What this means is that the statement that you are running is too obscure.
What you need to do to avoid this is to explicitly define the tables and columns that you are attempting to access and thus be implicit in your statements.
As a rule of thumb try and always define your columns in the following format:
{table_name}.{column_name}
With that being said the following should work:
$friends = implode("','", $friends);
/* implode the friends array for sql query. */
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends') AND text_post.username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Also I would also recommend that you use PHP's PDO Object as appose to the mysqli_query method.
I trust this helps.
both tables have a username. specify it using table.username
apparently both tables have the same column, and you are not prefixing the username column with either table name.
Maybe what you want is a union?
Use table prefix users in where block i.e. users.username
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con));
Try this:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT users.last_name,text_post.body FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Your logic would work were it not for username being present in both tables. Because it is, you need to alias your table names so that you can uniquely identify which column you're trying to use in the where clause:
SELECT * from users AS u, text_post as tp
WHERE u.username IN(....)
or shorter:
SELECT * from users u, text_post tp
WHERE u.username IN(....)
As a side note, it's bad practice to SELECT *, you should always explicitly select the columns you want, otherwise your code may crash if you add a column to a table later and forget to update your for loop to include/ignore any changed columns.

PHP MySQL - selecting values from table 1 which are not in table 2

This may be simple to solve but I'm having trouble with this piece of code - I'm a self taught newbie with PHP, and the code I've come up with doesn't seem to want to work.
The pages are for an online entry system for a sports competition. Judges' details are stored in table "club_judges", and users can enter them into a competition by copying them into "competition_judges". This is done via a checkbox form in a table.
I want to add functionality whereby judges who are already added to the competition do not appear in the import form, however my code does not seem to work. I am using a unique field of "bg_number" (the sport's identification number) to search for an existing entry.
Current code:
$existing_judges = mysql_query("SELECT bg_number FROM competition_judges WHERE competition='Test Competition'");
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$existing_judges_array = "('" . implode( "', '", $existing_judges_fetch ) . "');" ;
$query = "SELECT * FROM club_judges WHERE (`club`='Test Club') AND (`bg_number` NOT IN '$existing_judges_array') ORDER BY name ";
$result = mysql_query($query) or die(mysql_error());
Error displayed:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''('1234567', '1234567');') ORDER BY name' at line 1
For reference 1234567 is the bg_number for my test judge.
Any help would be greatly appreciated!
why dont u use just one query
SELECT *
FROM club_judges
WHERE `club`='Test Club'
AND `bg_number`
NOT IN (SELECT bg_number FROM competition_judges WHERE competition='Test Competition')
ORDER BY name
Use can use a single query instead like this:
$query = "SELECT * FROM `club_judges` WHERE `club`='Test Club'
AND
`bg_number` NOT IN
(SELECT `bg_number` FROM `competition_judges` WHERE `competition`='Test Competition')
ORDER BY `name` ";
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$result = mysql_query($query) or die(mysql_error());
here's a JOIN version
SELECT a.*
FROM club_judges a
LEFT JOIN competition_judges b
ON a.bg_number = b.bg_number AND
b.competition='Test Competition'
WHERE b.bg_number IS NULL AND
a.club = 'Test Club'
ORDER BY a.name
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

PHP SQL Select From Where

I am having some difficulty running some SQL code.
What I am trying to do is, find a row that contains the correct username, and then get a value from that correct row.
This is my SQL in the php:
mysql_query("SELECT * FROM users WHERE joined='$username' GET name")
As you can see, it looks for a username in users and then once found, it must GET a value from the correct row.
How do I do that?
You need some additional PHP code (a call to mysql_fetch_array) to process the result resource returned by MySQL.
$result = mysql_query("SELECT name FROM users WHERE joined='$username'");
$row = mysql_fetch_array($result);
echo $row['name'];
mysql_query("SELECT `name` FROM users WHERE joined='$username' ")
Just select the right column in your 'select clause' like above.
Edit: If you are just starting out though, you might want to follow a tutorial like this one which should take you through a nice step by step (and more importantly up to date functions) that will get you started.
mysql_query("SELECT name FROM users WHERE joined='$username'")
$q = mysql_query("SELECT * FROM users WHERE joined='$username'");
$r = mysql_fetch_array($q);
$name = $r['user_name']; // replace user_name with the column name of your table
mysql_query("SELECT name FROM users WHERE joined='$username' ")
Read documentation : http://dev.mysql.com/doc/refman/5.0/en/select.html

Trying to get data from mysql table via php with IN clause (favorites)

Here is how my table "User" looks:
Name Password Favorites
Test Test 1 2 3 4
And in my table "Data" I have
Comment ID
"Test" 2
I want the the user to be able to save a comment to its favorites, hence the first table, where I save all favorites in one row, so the table doesn't get too big.
I try to get them all back by implode and IN clause.
Right now it does not seem to work and I hope that maybe someone here could give me some useful input on how to conquer this problem :)
$favoritenstring = ($GET_["favoritenstring"]);
$query = "SELECT * FROM $table_id WHERE ID in ('" . implode("','",$favoritenstring) . "')";
Right now I am getting this error on the above query line:
Invalid arguments passed
Your have to remove slashes from the string first:
$string = stripslashes($favoritenstring);
$query = "SELECT * FROM $table_id WHERE ID in " .$string;
Change This...
From
($GET_["favoritenstring"]);
TO
($_GET["favoritenstring"]);
Try this:
$query = "SELECT * FROM $table_id WHERE ID in ( ";
$myVars=explode($favoritenstring);
$numFavs=count(explode(' ', $favoritenstring));
for($i=0;$i<$numFavs;$i++)
{
$query.=$myVars[$i];
if($i<($numFavs-1))
{
$query.=", ";
}
}
$query.=");";

inserting array into query then looping through results into new query

basically this is on the end of a dynamic form where the user can add multiple users of however many they want to a group, so i storte all the inputs in an array user[].
I want to query the array values and gain the userid for each then run another query with the user ids, inserting the userids into another table.
I am a beginner so I am getting lost in this. I looked at trying to use a for each method but couldnt get that working so now im trying a while.
here is my code ive been playing around with, i imagine its completely wrong :(
$query = 'SELECT * FROM users_tb WHERE student_number IN('.implode(',', $array).')';
mysql_query($query) or die(mysql_error());
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) VALUES('$group','$row['user_id']')";
mysql_query($sql) or die(mysql_error());
mysql_close();
}
please help? :D
regards
You want to use INSERT SELECT:
INSERT INTO group_association (group_id, user_id)
SELECT ' . $group_id . ', user_id
FROM users_tb WHERE student_number IN('.implode(',', $array).')
You have some extra quotes in the INSERT query, it should look like this:
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) ".
"VALUES('$group','$row[user_id]')";
Other than that, it looks like it should work if $group is a group id.

Categories