Select from DB where VALUES NOT EQUALS = array - php

im doing something where users has a local database and when he clicks to checks new books, it get all the IDS(fixed) form his local database and create String separeted by comma (1,2,3,4,5) and then do a GET to my server
www.myserver.com/getNews?ids=1,2,4,10
and in the server side i do this:
1) Get the last ID(fixed) and set in a var called $total
2) get the IDS send by the user and create a array using .explode(",")
3) get the missing values $missing = array_diff(range(1,$total),$ids);
get max id and get the missing numbers between the $total and $ids
and here come the part that i think its heavy:
for each $missing value i do a select and build a array to display as json
foreach($missing as $m) {
$sql = "SELECT * FROM `books` WHERE id='$m'";
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = array_map('utf8_encode', $row);
}
}
echo json_encode($emparray);
this is the only one approach or is there any other more light function?

you can try this way. Implode your array with comma then use NOT IN condition in your query to select all books you want.
$strMissing = implode(',', $missing);
$sql = "SELECT * FROM `books` WHERE id NOT IN (".$strMissing.")";

Related

get data from two tables and collect them in array and count rows of one table result

I had two tables named fixture_list and OneRecord where fixture_list has 3 columns named Team1, Team2, player whereas OneRecord has columns like Team1, Team2, id, status so here I want to select all the data of fixture_list and put them into array whereas I want to count the number of rows based on this where condition fixture_list.Team1=OneRecord.Team1 and
fixture_list.Team2=OneRecord.Team2 from OneRecord, actually I am not able to distinguish between selecting the data and putting it into the array and counting the number of rows because I just want to count the rows of one record only. I know things like joins and mysqli_multi_query() can be performed but do not know how...I want to perform this thing in single query please help.
<?php
require_once('connect.php');
$sql = "select * from fixture_list";
if($res = mysqli_query($con,$sql)){
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('players'=>$row[3],
'team1_name'=>$row[1],
'team2_name'=>$row[2]
));
}
mysqli_free_result($res);
}
echo json_encode (array("list"=>$result));
mysqli_close($con);
?>
You can use a sub_query to do this. I don't understand your question perfectly (try using capitals and punctuation marks), but this should be probably the format to use.
$sql = "SELECT `fixture_list`.`team1_name`,
`fixture_list`.`team2_name`,
(
SELECT count(`OneRecord`.`Team1`) as `total`
FROM `OneRecord`
WHERE `OneRecord`.`Team1` = `fixture_list`.`Team1`
AND `OneRecord`.`Team2` = `fixture_list`.`Team2`
) as `Total_Players`
FROM `fixture_list`
GROU BY `fixture_list`.`id`";
$result = array(); // keep this outside the while loop to ensure the array is made
if($res = mysqli_query($con,$sql)){
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$result[] = $row;
}
}
This would give you a $result array as follows:
array(
'team1_name' => 'TEAMNAME1',
'team2_name' => 'TEAMNAME2',
'Total_Players' => INTEGER_VALUE
)
The INTEGER_VALUE is the number of rows from the subquery. You can edit the WHERE part of the subquery to your liking
Then you can do this to create a json object:
echo json_encode($result);
This will echo it, which is ideal if you use it with an Ajax function for example.

Retrieving values from MySQL using php

Here i have made an MySQL which has the columns of "id","name","username","email",age" . Where even i made the the PHP code to retrieve the data for the given id.
eg:if the user enter id=3 then it shows the datas corresponding to the id.
But now i want set multiple inputs so that user can type more than one id and it list the corresponding datas of the particular id.
My PHP Code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM user WHERE id='".$id."'";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)){
array_push($result,array(
"id"=>$res['id'],
"name"=>$res['name'],
"username"=>$res['username'],
"email"=>$res['email'],
"age"=>$res['age']
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
Now this URL gives the perfect result:
"http://www.allwaysready.16mb.com/Sort.php?id=4"
Now how can i get the corresponding values for the multiple id's?
You can use array syntax to pass multiple IDs to your script and use MySQL's IN() to query against them all at once.
URL: http://www.allwaysready.16mb.com/Sort.php?id[]=4&id[]1&id[]=2
$ids = $_GET['id'];
$ids = array_map(function($id) {
return (int) $id;
}, $ids);
$ids = implode(',', $ids);
$sql = "SELECT * FROM user WHERE work IN($ids);
I cast the IDs to integers because your current code is wide open to SQL injection. You really should be using paramterized queries.
Use the "IN" condition:
If id is a number:
SELECT * FROM user WHERE id IN (89, 25);
If id is a string, put the id's in quotes:
SELECT * FROM user WHERE id IN ('89N', '15B', '25E');
Rewrite your query in PHP to use the In Query condition, paying close attention to your column definition data types. Strings must be quoted for example.

Explode multiple user Ids

Im having trouble getting explode to work I have a table field named Attending with multiple user Ids separated with commas 73,1,5 right now i can easily get user 73 to echo out but need explode for the rest, I want it to echo out each username of those 3 users or however many it ends up being. I was thinking it might be something like what i commented out with the //
Attending Field is list of users
http://imageshack.us/a/img38/1425/eventsne.jpg
Trying to Echo out like this once i get username working ill do the avatar and in a table
http://imageshack.us/a/img819/8210/events2d.jpg
$Attending1 = array();
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
//$AttendingUserIds = $Attending1['Attending'];
//$AttendingExploded = explode(",", $AttendingUserIds);
//$Attending3 = array();
//$Attending3 = mysql_query("SELECT * FROM Events, Users WHERE $AttendingExploded = Users.UserId");
while ($Attending2 = mysql_fetch_array($Attending1)) {
echo $Attending2['username'];
}
Just tryed KyleK 3rd suggestion
$Attending1 = array();
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
$AttendingUserIds = $Attending1['Attending'];
//$AttendingExploded = explode(",", $AttendingUserIds);
$Attending3 = array();
$Attending3 = mysql_query("SELECT * FROM Events, Users WHERE Users.UserId IN ($AttendingUserIds)");
It gives me Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource where the While starts.
You can do it all in just one SELECT, by joining Events and Users tables thru the find_in_set() function. That way, you will get all users which attended each event, because find_in_set() will look up the first parameter in the CSV string supplied as the second parameter. You may also want to add a WHERE to filter a specific event. And don't forget to replace the * with only the fields you need, to avoid unnecessary data traffic:
$Attending = array();
$Attending = mysql_query("
SELECT *
FROM Events e
INNER JOIN Users u ON find_in_set(u.UserId, e.Attending)
");
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
while ($Attending2 = mysql_fetch_assoc($Attending1)) {
$arr[] = $Attending2['username'];
}
mysql_query doesn't give you an array, fetch_array (or fetch_assoc) does.
Its result will be similar to this: $arr[0]['username'], $arr[1]['username'], $arr[2]['username'], etc. I don't know how you want to "explode" so I can't answer, but after fetch_assoc you should get an array.
So if I understand you correctly you have values in a string that are comma seperated "73, 3, 5".
So then just use WHERE IN
Your string of values from the database, however you gonna get it...
$stringofids = "73,3,3";//You will obviously retrieve these from database
Then just pass that string into another query, with a WHERE IN statement...
That will return an array of all the users attending.
$AttendingUsers = mysql_query("SELECT * FROM Events, Users WHERE Users.UserId IN ($stringofids)");
while ($Attending = mysql_fetch_array($AttendingUsers)) {
echo $Attending['username'];
}

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Sorting the results of a mysql query

Im having difficulties trying to figure out an elegant solution to sorting the results of a mysql query based on a delimited string. Ill explain in more detail below
I am creating a database of contacts where individual users can add/remove people from a list. When the user adds a new contact I append the added contact id to a delimited string and store that data in a database column associated with that user (named contacts):
$userID = ?? //YOUR ID
$contactID = ?? //WHATEVER THE ADDED USER ID IS
$confirm = 0 //has the user been confirmed
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contact = $row['contacts'];
$contact .= '|'.$contactID.':'.$confirm;
$update = mysql_query("UPDATE user SET contacts = '$contact' WHERE id = '$userID'");
//contact column data might be: |10:0|18:0|36:0|5:0
When the user searches their contacts I grab the data from the contacts column, explode/split the string and return the individual users names:
$userID = ?? //YOUR ID
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contacts = explode("|", $row['contacts']);
foreach($contacts as $item)
{
list($contactID,$confirm) = split(":", $item);
$sql = "SELECT name FROM ".user." WHERE id = '$contactID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
echo($row['name'].'<BR>');
}
This indeed does return all the names, but it returns them in the order of the delimited string. I cant seem to find an elegant way to sort by name alphabetically.
Should I not store the contacts list in a delimited string? How would you solve this?
You're right, you should not store the contacts in a string. Instead use another table which contains the user information. The new table should look something like the following:
Table: user_contacts
| user_id | contact_id | confirm |
-------------------------------------------
| your data here... |
Then when you need your contact list you can simply perform another query:
SELECT * FROM `user_contacts`
JOIN `users` ON `users`.`id` = `user_contatcs`.`user_id`
WHERE `users`.`id` = $id
ORDER BY `users`.`name`;
Or however you need to order it.
There are two obvious approaches:
Sort the results once you've fetched them
Fetch them all in one query and have the DB sort them
For #1, use usort():
$rows = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$query = mysql_query("SELECT name FROM user WHERE id = '$contactID'");
$rows[] = mysql_fetch_array($query);
}
usort($rows, 'sort_by_name');
function sort_by_name($a, $b){
return strcmp($a['name'], $b['name']);
}
foreach ($rows as $row){
echo($row['name'].'<BR>');
}
For #2, build a list of IDs and use IN:
$ids = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$ids[] = $contactID;
}
$ids = implode(',', $ids);
$query = mysql_query("SELECT name FROM user WHERE id IN ($ids) ORDER BY name ASC");
while ($row = mysql_fetch_array($query)){
echo($row['name'].'<BR>');
}
If you're using a relational database, then what you want is a separate table that stores person-contact relationships. Then you would modify your sql query to select based on a join across two tables
SELECT * FROM person, contact
JOIN contact ON person.id = contact.personid
JOIN person ON contact.contactid = person.id
WHERE person.id = $id
ORDER BY person.lastname
(That code is probably not quite correct.)
If you're using a no-sql type implementation, the way you're doing it is fine, except that you will either have to programmatically sort after the fact, or sort-on-insert. Sort on insert means you'd have to query the current list of contacts on inserting one, then sort through to find the right position and insert the id into the delimited string. Then save that back to the db. The downside to this is you'll only be able to sort one way.
Generally, people use relational databases and 'normalize' them as described above.

Categories