Extracting several elements using php - php

I have these two tables in my database :
table_A: table_B:
id user id user
1 Mike 1 Mike
2 Dan 2 Dan
3 Tom 3 Tom
4 Lina 4 Lina
5 Cynthia
6 Sam
And i'm using this SQL query, to detect which users in table_B do not exist in table_A, and select those users (not existing in table A) ids:
SELECT table_B.id FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);
And i'm using this php script to put the ids in a variable $not:
$sql=" SELECT table_B.id FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A)";
$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
while($row = mysqli_fetch_array($result)){
$not=$row[0];
}
Now if i want to extract 2 elements with my sql query:
SELECT table_B.id, table_B.name FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);
How can i place both, each in a variable using the above script, so i'll be able to insert each element in a different table in the database?

You can put the values in a multidimensional array.
$not = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$not[] = array(
"id" => $row['id'],
"name" => $row['name']
);
}
echo $not[0]['id']; //Returns 5
echo $not[0]['name']; //Returns Cynthia
echo $not[1]['id']; //Returns 6
echo $not[1]['name']; //Returns Sam

in your query define table_B.id as user_id and table_B.name as user
then in your php use mysqli_fetch_object like this
while($row = mysqli_fetch_object($result)){
$not= $row;
//or if you want to store all the results use $not[] = $row; and define $not as array
}

Related

Best practice for writing code in php for foreach->foreach->if(1st loop id == 2nd loop id)->result

First loop table
user_id | fname | lname
1 | first | emp
2 | second| emp
3 | third | emp
Second loop table
shift_id | employee_id
1 | 1
2 | 2
3 | 2
if($employees)
{
foreach ($employees as $employee)
{
if($employee['user_id'] == $shift['employee_id'])
{
echo ucwords($employee['fname']. ' ' .$employee['lname']);
}
}
}
I am getting the right result but I think there is some better way of writing this.
You can use joins in table. Left join means that the user line has to exists (because: LEFT) and the shifts enty is optional.
SELECT user.user_id, user.fname, user.lname, shifts.shift_id
FROM yourUserTable AS user
LEFT JOIN yourShiftsTable AS shifts ON(user.user_id = shifts.employee_id)
Now you get it in your initial array, as if you'd select it as one row from a table and no longer need to do tricks in PHP to combine information. If you can, always try to get the database to manage data, it does that way faster than PHP can.
Please note, the query could be a little off, I just wrote this out of the top of my head.
Just some test code I whipped up to test this from the information provided for this "Demonstration Code".
Note: I have used the mysqli class for the database (instantiating $db ) and have excluded the SQL Table setup.
What you would have had is something along the lines of this...
Case 1 - The original
$db = new mysqli('localhost', 'root', 'test', 'phptutorials_st26');
echo '<h2>Create $employees </h2>';
$query = "SELECT * FROM users";
$result = $db->query($query);
$employees = $result->fetch_all(MYSQL_ASSOC);
var_dump($employees);
echo '<h2>Create $shifts </h2>';
$query = "SELECT * FROM shifts";
$result = $db->query($query);
$shifts = $result->fetch_all(MYSQL_ASSOC);
var_dump($shifts);
echo '<h2>Using foreach on $employees and $shifts</h2>';
if ($employees) {
foreach ($employees as $employee) {
foreach ($shifts as $shift) {
if ($employee['user_id'] == $shift['employee_id']) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
}
}
}
The Result from the above is
First Emp
Second Emp
Second Emp
Case 2 - Using a Join
Well using a join, as everyone has already stated, is the way to go...
$sql = "SELECT u.user_id, u.fname, u.lname, s.shift_id
FROM users AS u
JOIN shifts AS s ON(u.user_id = s.employee_id)
";
$result = $db->query($sql);
$employees = $result->fetch_all(MYSQL_ASSOC);
// To see what comes out because we always check things.
var_dump($joined_result);
(Don't ask me why I love using very abbreviated aliases for the table names! It's just "a thing".)
Then your "loop" simply becomes...
echo '<h2>Using foreach on join</h2>';
foreach ($employees as $employee) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
And the result is...
First Emp
Second Emp
Second Emp
Case 2 - has reduced the code and only requires 1 Trip to the Database.
Does that help you any?
You could do it this way also. Its a little shorter.
SELECT TABLE1.FNAME, TABLE1.LNAME, TABLE2.EMPLOYEE_ID
FROM TABLE1, TABLE2
WHERE TABLE1.USER_ID = TABLE2.EMPLOYEE_ID;

Most Efficient way to MySQL Query inside query

i'm just learning PHP, and i have a question
Let just say, i have MySQL table "A"
Name | Job
--------|---------
Jynx | 1
Micah | 4
Nancy | 3
Turah | 1
And another table "B"
JobId | JobName
-------|-----------
1 | Lawyer
2 | Architec
3 | Farmer
4 | Mage
5 | Warrior
So supposedly in php i want to draw table that showed the content of table "A", but instead of displaying number at the "Job" colomn, they each display Job names from Table "B".
What is the most efficient way to do that?
For now, i just thinking of using
$conn = My database connect setting
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>";
$sql2 = "SELECT * FROM tableB WHERE JobId=$row['Job']";
$result2 = $conn->query($sql2);
while($row2 = mysqli_fetch_assoc($result2)) {
echo "<td>". $row2['JobName'] ."</td></tr>;
}
}
But wouldn't it take a lot of calculating proccess if there is multiple similliar colomn with hundreed of rows?
Is there any more efficient way to do this?
Sorry for my bad english
Thank you for your attention.
A join is definitely the way to go here.
SELECT a.Name, b.JobName
FROM tableA a
JOIN tableB b on (a.Job = b.JobId)
ORDER BY a.Name
Well, it is not easy to learn about JOIN, no time for now, but i will get to learn it latter.
As for now, i just get the idea to just use ARRAY instead
So before i draw the main table, i assign the supportive table (Table B) into associative array
$sql = "SELECT * FROM tableB ORDER BY Id";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$job[$row['JobId']] = $row['JobName'];
}
And at the main table
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>". $job[$row['Job']];
}

How can sort records by low value. All record in same row in my table

How can i sort the records with same values:
This is the example of values currently i have in my table
record_id a_id b_id c_id a_value b_value c_value
25 A B C 450 390 395
Sorry im not able to create table here.
I'm using Php/MySQL Backend.
I need the following output:
B 390
C 395
A 450
It should be sort by lower value with the id name as well.
I know if all these records in different different rows. it was easy to sort by small value. buy using MIN function of mysql.
Im not sure how to sort this in same row records.
You can accomplish this with php, for example:
<?php
$row = ...
$myArray = array(
'A' => $row['a_value'],
'B' => $row['b_value'],
'C' => $row['c_value'],
);
asort($myArray);
echo '<pre>';
print_r($myArray);
echo '</pre>';
If you like to make it dynamic then you can do something like this:
<?php
$row = ...
$myArray = array();
foreach ($row as $column => $value) {
if (strpos($column, '_value') !== FALSE) {
$myArray[strtoupper(substr($column, 1))] = $value;
}
}
asort($myArray);
echo '<pre>';
print_r($myArray);
echo '</pre>';
SELECT record_id, mim(
SELECT a_value FROM table t2 WHERE t1.record_id = t1.record_id UNION ALL
SELECT b_value FROM table t3 WHERE t3.record_id = t1.record_id UNION ALL
SELECT c_value FROM table t4 WHERE t4.record_id = t1.record_id )
FROM table t1
Your sql should fallow the logic above. I canĀ“t test as i dont have mysql in this pc.

SQL: can I JOIN 2 tables according the first table "array" value?

Im trying to find a better way to return 2 tables at once.
My first table is:
[ID] [area]
1 13,12,15
6 18,17,13
and the second table is:
[areaname] [singlearea]
textOf12 12
textOf18 18
textOf15 15
Now, I need to return for each [ID] hits area names, for example:
For the ID: 1, I need the following array: (textOf12,textOf15)
and for the ID 6 I need: (textOf18) only.
This is what i have for now (I don't think its a nice code):
$getall = "SELECT * FROM table1";
$resultfull = mysql_query($getall);
while ($res = mysql_fetch_assoc($resultfull))
{
$uarray = array();
$sqlarea = explode(",", $res['area']);
foreach($sqlarea as $userarea)
{
$areaarray = runquery("SELECT areaname From table2 WHERE singlearea = '".$userarea."'");
$value = mysql_fetch_object($areaarray);
array_push($uarray,$value->areaname);
}
var_dump($uarray);
any suggestions?
Thank you very much!
Comma separated ID list and ID value pretty good matching using like:
select t1.id, t2.areaname
from table1 t1, table2 t2
where concat(',', t1.area, ',') like concat('%,', t2.singlearea, ',%')
However It's recommended to use additional link table!

Selecting a value by row number

I have the following MySQL table:
table_1
id | value_1 | value_2 | value_3
1 hehe haha stack
2 over flow me
3 123 abc hello
4 hi random php
5 html js css
How can I select value_2 from 3rd row, which is "abc"?
Something like $rows[3]['value_2']
Here's the code I had tried with:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
$rows=mysql_fetch_array($sql);
//And then I tried accessing it by "$rows[3]['value_2']" and $rows['value_2'][3]
I can't use SELECT * FROM table_1 WHERE id='3', because I need to access multiple lines (all of them). I can't use a WHILE loop also, because I need the values in very different places in the code.
mysql_fetch_array only returns a row corresponding to the query. The proper use of mysql_fetch_array is as such:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
while ($row = mysql_fetch_array($sql)) {
printf("ID: %s value_2: %s", $row[0], $row[2]);
}
http://www.php.net/manual/en/function.mysql-fetch-array.php
Found the answer. You can now access them how you wanted.
$sql=mysql_query("SELECT * FROM settings ORDER BY `settings`.`id` ASC");
$id=0;
while ($rows = mysql_fetch_array($sql)) {
$settings[$id]['value_1']=$rows['value_1'];
$settings[$id]['value_2']=$rows['value_2'];
$settings[$id]['value_3']=$rows['value_3'];
$id++;
}
echo $settings[5]['value_3'];
echo $settings[5]['value_1'];
echo $settings[4]['value_2'];
echo $settings[0]['value_3'];

Categories