sql using LIKE clause : php - php

I'm trying to generate a list of events that a user is attending. All I'm trying to do is search through columns and comparing the userid to the names stored in each column using LIKE.
Right now I have two different events stored in my database for testing, each with a unique eventID. The userid i'm signed in with is attending both of these events, however it's only displaying the eventID1 twice instead of eventID1 and eventID2.
The usernames are stored in a column called acceptedInvites separated by "~". So right now it shows "1~2" for the userid's attending. Can I just use %like% to pull these events?
$userid = $_SESSION['userid'];
echo "<h2>My Events</h2>";
$myEvents = mysql_query("select eventID from events where acceptedInvites LIKE '%$userid%' ");
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
My output is just 11 when it should be 12

Change your table setup, into a many-to-many setup (many users can attend one event, and one user can attend many events):
users
- id (pk, ai)
- name
- embarrassing_personal_habits
events
- id (pk, ai)
- location
- start_time
users_to_events
- user_id ]-|
|- Joint pk
- event id ]-|
Now you just use joins:
SELECT u.*
FROM users u
JOIN users_to_events u2e
ON u.id = u2e.id
JOIN events e
ON u2e.event_id = e.id
WHERE u.id = 11

I'm a bit confused by your description, but I think the issue is that mysql_fetch_array just returns one row at a time and your code is currently set up in a way that seems to assume $fetch is filled with an array of all the results. You need to continuously be calling mysql_fetch_array for that to happen.
Instead of
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
You could have
while ($row = mysql_fetch_array($myEvents)) {
echo $row['eventID'];
}
This would cycle through the various rows of events in the table.

Instead of using foreach(), use while() like this:
$myEvents = mysql_query("SELECT `eventID` FROM `events` WHERE `acceptedInvites` LIKE '".$userid."'");
while ($fetch = mysql_fetch_array($myEvents))
{
echo $fetch['eventID'];
}
It will create a loop like foreach() but simpler...
P.S. When you make a MySQL Query, use backticks [ ` ] to ensure that the string is not confused with MySQL functions (LIKE,SELECT, etc.).

Related

Check First on Table A, if not found Check on other table

I am creating a Log in and I have separate tables for Users A and Users B.
What I want to do is check first in first table if the Users that trying to Login is in the Table A,
if YES, it will not go to the Table B to check the Login credentials, if NOT, go to Table B and check the Login credentials.
Table A
SELECT * FROM tableA WHERE userId='$userId' AND password='$password'
Table B
SELECT * FROM tableB WHERE accountNumber='$accountNumber' AND password='$password'
Note: The 2 Tables has different Field Name userId and accountNumber.
I presume you are fetching the values of username and password from client side so I will tell you only what you asked for.
$getUserBasic1=$db->prepare('SELECT * FROM tableA WHERE userId="$userId" AND password="$password"');
$getUserBasic1->execute();
$user= $getUserBasic1->fetchAll();
if(count($user)>0)
{
//if yes do what you want here
}
else
{
$getUserBasic2=$db2->prepare('SELECT * FROM tableB WHERE accountNumber="$accountNumber" AND password="$password"');
$getUserBasic2->execute();
$user2= $getUserBasic2->fetchAll();
//write your code here
}
You could use an INNER JOIN and select both table results taking Table A's result first if it exists, else take Table B's result.
Assuming both tables have some sort of reference like the User ID you can use something like this:
SELECT tbla.*, tblb.* FROM tableA tbla
INNER JOIN tableB tblb ON tbla.userId = tblb.userId
WHERE userId='$userId' OR accountNumber='$accountNumber' AND password='$password'
ORDER BY userId ASC
LIMIT 1
The query above uses the cross-reference (userId in this case) and joins both tables together before querying the results. It orders the results by Table A before Table B but limits the result to 1 bringing either Table A or Table B out depending which is null.
Try combining the tables, some thing like:
SELECT * FROM tableA, tableB WHERE tableA.userId='$userId' AND tableA.password='$password' OR tableB.accountNumber='$accountNumber' AND tableB.password='$password'
I have not checked, so may not work, but see if this gets what you are looking for!
Something like this:
$sql = "SQL QUERY FOR TABLEA";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// checking if result in TABLE A
}
else{
//search in TABLE B by updating your sql value.
}
I hope that you want to check for the registered user, the best way to do that is to keep one table and just search there itself keeping the userID as the primary key.

Why do i double my display in json

So i fetch my data from two tables in my php and encode it in one json object. I got everything i needed except that it doubles the display. And my teamone is located in the matches tables. instead of starting from array 0, it starts after the schedules tables. Which is array 7. I dont know why this happen.
Here is my php.
$sql = "SELECT * from schedule, matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("start"=>$row[4],"end"=>$row[5],"venue"=>$row[6], "teamone"=>$row[8], "teamtwo"=>$row[9],
"s_name"=>$row[17]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
Here is my display. As you can see there are four displays but in my database it only has 2. It doubles the display. How do i fix this? Thanks
{ "schedule_response":[
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"}]}
I need to get the teamone, teamtwo and s_name values from the matches while i need the start, end and the venue from the schedule table in one query.
Schedule table
Matches Table
Because of your SQL query, you should not forget to perform some form of a grouping (the way you select results from both table defines that):
$sql = "SELECT * from schedule s, matches m GROUP BY s.id"; //I assume that your table schedule has an `id`
Or, you can rework the query to be more readable:
$sql = "SELECT s.*, m.* FROM schedule s
INNER JOIN matches m ON m.schedule_id = s.id
GROUP BY s.id"; //I assume that you have such database design that you have defined foreign key on table `matches`.
Of course, the INNER JOIN above could be LEFT OUTER JOIN - it all depends on your database design.
I think it is the problem with mysqli_fetch_array().
Can you please change mysqli_fetch_array() to mysqli_fetch_assoc()

Retrieving specific ID once

I have a table named users and has a user_id, and a table named groups and has a group_id and also have user_id that is a foreign key reference from users's user_id.The situation is here: if the user joined a group, his/her user_id is inserted into table groups. So if the user joined two different groups, the column 'user_id' in table 'groups' will insert two or more same user_id's. Well, I just want to bring the user_id once, either he/she joined two or more groups..
I have no idea how to loop it properly without getting user_id that is the same.... I just want it to loop once...
$query_groups = mysql_query("SELECT * FROM groups");
while ($rows_g = mysql_fetch_assoc($query_groups)) {
$g_user_id = $rows_g['user_id'];
$query_users = mysql_query("SELECT * FROM users WHERE user_id='$g_user_id'");
while ($rows_u = mysql_fetch_assoc($query_users)) {
echo $rows_u['user_id'];
}
}
change your code as follows:
$query_groups = mysql_query("SELECT user_id FROM groups LEFT JOIN users ON users.user_id = groups.user_id GROUP BY groups.user_id");
while($rows = mysql_fetch_assoc($query_groups))
{
echo $rows['user_id'];
}
You are using $rows_g but the variable is namend $rows in the first while loop.
Wrong:
$g_user_id = $rows_g['user_id'];
Correct:
$g_user_id = $rows['user_id'];
But try to use joining tables, because this is an inefficient way to get the wanted data.
In your case you should use LEFT JOIN.

how to extract mysql data into json using php

i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.

Foreach or Inner join? -- that is the PHP question

I have 2 tables. One (artWork) with all the data I want to pull from, including 2 cols of id's. The other (sharedWork) has the same 2 id cols that are also in the first -- but none of the essential data I want to echo out. Objective: use the id's in both table to filter out row in the first (artWork). See below in the code what I tried that didn't work
I also tried to figure out an inner join that would accomplish the same. No luck there either. Wondering which would be the best approach and how to do it.
thanks
Allen
//////// Get id's first ///////////
$QUERY0="SELECT * FROM artWork WHERE user_id = '$user_id' ";
$res0 = mysql_query($QUERY0);
$num0 = mysql_num_rows($res0);
if($num0>0){
while($row = mysql_fetch_array($res0)){
$art_id0 = $row['art_id'];
}
}
$QUERY1="SELECT * FROM shareWork WHERE user_id = '$user_id' ";
$res1 = mysql_query($QUERY1);
$num1 = mysql_num_rows($res1);
if($num1>0){
while($row = mysql_fetch_array($res1)){
$art_id = $row['art_id'];
}
}
$art_id2 = array_merge($art_id0, $art_id1);
foreach ($art_id2 as $art_id3){
$QUERY="SELECT * FROM artWork WHERE art_id = '$art_id3' ";
// echo "id..".$art_id0;
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$art_title = $row['art_title'];
$art_id = $row['art_id'];
etc................and so on
.........to....
</tr>";
}
}
}
Don't query your database inside a loop unless you absolutely have to.
Everytime you query the database, you're using disk I/O to read through the database and return your record. Disk I/O is the slowest read on a computer, and will be a massive bottleneck for your application.
If you run larger queries upfront, or at least outside of a loop, you will hit your disk less often, improving performance. Your results from larger queries will be held in memory, which is considerably faster than reading from disk.
Now, with that warning out of the way, let's address your actual problem:
It seems you're trying to grab records from artWork where the user is the primary artist, or the user was one of several artists to work on a group project. artWork seems to hold the id of the primary artist on the project whereas shareWork is probably some sort of many-to-many lookup table which associates user ids with all art projects they were a part of.
The first thing I should ask is whether or not you even need the first query to artWork or if the primary artist should have a record for that art_id in shareWork anyway, for having worked on the project at all.
If you don't need the first lookup, then the query becomes very easy: just grab all of the users art_ids from shareWork table and use that to lookup the his or her records in the main artWork table:
SELECT artWork.*
FROM artWork
WHERE art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
If you do need to look in both tables, then you just add a check in the query above to also check for that user in the artWork table:
SELECT artWork.*
FROM artWork
WHERE
user_id = $user
OR art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
This will get you all artWork records in a single query, rather than.. well, a lot of queries, and you can do your mysql_fetch_array loop over the results of that one query and be done with it.

Categories