So I have a two tables users (IDN,RoP) and search_info (IDN, Location, Age) (IDN - is a key column )
I need collect and count the rows from database which have a correct type(RoP) and correct information (Location and Age).
so php :
$location = $_POST['location'];
$age = $_POST['age'];
$type=$_SESSION['type'];
so then I make mysql code...it is doesn't select raws but it is count them. I know that query is not used anymore, but I used it for educational purpose.
$search_result= mysql_query("
SELECT COUNT(a.IDN)
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
$search=mysql_fetch_array($search_result);
So as you can see the code is working but here the staff. I sent the location 1, 2 or 3 , otherwise 0. So if location == 0 I would like to grab from database rows regardless location (in other words - ANY location). Similar with age. is it possible realize on MYSQL? How to change variable that MYSQL grab any location?
AND the last question in code. I'm trying to select requirement data, but have problem to output them. so how to print this out?
$search_result= mysql_query("
SELECT COUNT(a.IDN), a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search; // some how I get only first row not all of them
$i++;
}
First:
<?php
$location = (int) $_POST['location'];
$age = (int) $_POST['age'];
$type=$_SESSION['type'];
$and_where = array();
if( $age )
{
$and_where [] = "b.Age = '{$age}'";
}
if( $location )
{
$and_where [] = "b.Location = '{$location}'";
}
if( ! empty( $and_where ))
{
$and_where = ' AND ' . implode( ' AND ', $and_where);
} else {
$and_where = '';
}
$sql = "SELECT COUNT(a.IDN) ".
"FROM users AS a LEFT JOIN info_search AS b ".
"ON a.IDN = b.IDN Where a.RoP='{$s_type}'" . $and_where;
?>
Second:
$search_result= mysql_query("
SELECT COUNT(a.IDN) as cnt, a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search ['cnt']; // some how I get only first row not all of them
$i++;
}
Related
1- I'm building a comparison app which compares the relationship between two users.
If the user A and user B has the same country address then it will print alert to any of the same similar values.
2- There is another issue which is some users has multiple addresses for example user A has address x1 and user b has address x1 and address x2, in this scenario how do I compare user A's address with the multiple addresses with user B and alert that the address x1 is matched between the two users?
here is the queries for both users
$query1 = "
SELECT
a.PID, a.`Name`, a.Avatar, a.Email,
b.City, a.LDate, b.Country, b.MPhone,
b.Gender, b.Birthday
FROM
`Profile` AS a
LEFT JOIN Details AS b ON a.PID = b.PID
WHERE
a.PID = '1'
";
$UserInfo1 = mysqli_query($mysqli, $query1);
while( $row = mysqli_fetch_array($UserInfo1) ){
$Avatar1 = "{$row['Avatar']}";
$Name1 = "{$row['Name']}";
$Email1 = "{$row['Email']}";
$Country1 = "{$row['Country']}</td>";
$MPhone1 = "{$row['MPhone']}</td>";
$Gender1 = "{$row['Gender']}</td>";
$City1 = "{$row['City']}</td>";
$Birthday1 = "{$row['Birthday']}</td>";
}
$query2 = "
SELECT
a.PID, a.`Name`, a.Avatar, a.Email,
b.City, a.LDate, b.Country, b.MPhone,
b.Gender, b.Birthday
FROM
`Profile` AS a
LEFT JOIN Details AS b ON a.PID = b.PID
WHERE
a.PID = '2'
";
$UserInfo2 = mysqli_query($mysqli, $query2);
while( $row = mysqli_fetch_array($UserInfo2) ){
$Avatar2 = "{$row['Avatar']}";
$Name2 = "{$row['Name']}";
$Email2 = "{$row['Email']}";
$Country2 = "{$row['Country']}</td>";
$MPhone2 = "{$row['MPhone']}</td>";
$Gender2 = "{$row['Gender']}</td>";
$City2 = "{$row['City']}</td>";
$Birthday2 = "{$row['Birthday']}</td>";
}
3- The final results is that I want to make flowchart and point the matched information to each other something like this screenshot:
What would be the best and simplest way to make this comparison in php or Mysql?
Your help is highly needed and appreciated.
I am new to SQL and PHP. I have a requirement where the end user enters text in an HTML form, which I am storing in MySQL db. Later I query all the tables in the db which has the user data to obtain concatenated strings.
For a clearer understanding here is an image of my data and the desired result: Click for Image
Right now I am able to concatenate only one string based on a specific id with this query:
select group_concat(text order by T.did separator ' ') as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue,
concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid) as T
where T.id=0;
which gives me the result
| TTT |
--------------------------------
| A 20 year old Man is Fresher |
I know I can use a loop on id, but the problem is the ids are not fixed.
Note: There can be "n" number of dimensions and levels.
Here is an SQL Fiddle of the data I am trying to query: SQL Fiddle
I have edited your query to get what you wanted..
select did as groupid, group_concat(text order by dimensionid separator ' ' ) as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue, concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid
) as T
group by id;
I hope this helps you...
UPDATE :
using php..
$sql = "SELECT `dimensionid`, `dimensiontext`, `dimensiondescr` FROM `dimension`";
$dimensions = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='age') ";
$ages = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='sex') ";
$sexes = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='experience') ";
$experiences = mysqli_fetch_all (mysqli_query($con, $sql));
foreach ($ages as $age) {
foreach ($sexes as $sex) {
foreach ($experiences as $exp) {
foreach ($dimensions as $dimension) {
$putage = "";
$putsex = "";
$putexp = "";
if($dimension[2]=="Age"){
$putage = $age[0];
}elseif($dimension[2]=="Sex"){
$putsex = $sex[0];
}elseif($dimension[2]=="Experience"){
$putexp = $exp[0];
}
echo $str = $dimension['1']." ".$putage.$putsex.$putexp." " ;
}
echo "<br>";
}
echo "<br>";
}
}
I have this code how can I combine multiple queries and their result into one ?
<?php
$obj = new stdClass();
include('pdoConfig.php');
$response = array();
$sql1 = $dbh->prepare("select * from orders_assigned where delivery_status != 'Cancelled' && order_status='Picked'");
$sql1->execute();
$count1 = $sql1->rowCount();
if ($count1 >= 1) {
while ($row1 = $sql1->fetch()) {
$delivery_status = $row1['delivery_status'];
$deliveryboy_id = $row1['username'];
$order_id = $row1['order_id'];
$sql2 = $dbh->prepare("select * from delboy_login where id = ?");
$sql2->bindParam(1, $deliveryboy_id);
$sql2->execute();
$row2 = $sql2->fetch();
$del_name = $row2['name'];//name
$del_lat = $row2['lat'];//lat
$del_longi = $row2['longi'];//long
$del_icon = $row2['icon'];//icon
$sql3 = $dbh->prepare("select * from `order` where `order_id` = ?");
$sql3->bindParam(1, $order_id);
$sql3->execute();
$row3 = $sql3->fetch();
$address_id = $row3['address_id'];
$user_id = $row3['user_id'];
$sql4 = $dbh->prepare("select * from customer_login where cust_id = ?");
$sql4->bindParam(1, $user_id);
$sql4->execute();
$row4 = $sql4->fetch();
$cus_name = $row4['name'];//name
$sql5 = $dbh->prepare("select * from address where a_id = ?");
$sql5->bindParam(1, $address_id);
$sql5->execute();
$row5 = $sql5->fetch();
$cus_lat = $row5['lat'];//lat
$cus_longi = $row5['longi'];//long
$cus_icon = $row5['icon'];//icon
$tmp = array();
$tmp['lat'] = $del_lat;//i want use $cus_lat here too
$tmp['content'] = $del_name;//i want use $cus_name here too
$tmp['lng'] = $del_longi;//i want use $cus_longi here too
$tmp['icon'] = $del_icon;//i want use $cus_icon here too
array_push($response, $tmp);
}
}
echo json_encode($response, JSON_NUMERIC_CHECK);
Using this I can only get either $del_ data or $cus_ data I want use both. I have multiple tables for same data but I can not combine tables because both are different kind of users. As I am not good at joins so I don't know how to use joins here.
By using one of query provided below i am getting this
{
"delivery_status" : Delivered,
"username" : 1,
"order_id" : 5,
"del_name" : Boy One,
"del_lat" : 26.8808383,
"del_longi" : 75.7503407,
"address_id" : 31,
"user_id" : 1,
"cus_name" : Roylee Wheels,
"cus_lat" : 20.593684,
"cus_longi" : 78.96288
},
{
"delivery_status" : Processing,
"username" : 1,
"order_id" : 6,
"del_name" : Boy One,
"del_lat" : 26.8808383,
"del_longi" : 75.7503407,
"address_id" : 30,
"user_id" : 1,
"cus_name" : Roylee Wheels,
"cus_lat" : 20.594725,
"cus_longi" : 78.963407
},
and so on...
I want final output like this
{
"icon" : "icon path here",
"del_name" : "Boy One",
"del_lat" : 26.8808383,
"del_longi" : 75.7503407,
},
{
"icon" : "icon path here",
"cus_name" : "Roylee Wheels",
"cus_lat" : 20.594725,
"cus_longi" : 78.963407
},
and so on...
select orders_assigned.*, order.*, address.*
from orders_assigned
inner join delboy_login on delboy_login.id = orders_assigned.delboy_login
inner join `order` on `order`.`id` = orders_assigned.order_id
inner join customer_login on customer_login.cust_id = order.user_id
inner join address on address.a_id = order.address_id
where delivery_status != 'Cancelled' && order_status='Picked'
You need to join your tables. this is untested, so something like this.
It's bad practice to select * from tables, you should really be defining only the fields you need.
Also note that order is a reserved word in mysql so not a good name for a table - hence the backticks.
Try this : It will work !
SELECT oa.delivery_status, oa.username oa.order_id, dl.name, dl.lat, dl.longi, o.address_id, o,user_id, cl.name, a.lat, a.longi
FROM orders_assigned as oa
JOIN delboy_login as dl ON oa.username = dl.id
JOIN order as o ON oa.order_id = o.order_id
JOIN customer_login as cl ON = o.user_id = cl.cust_id
JOIN address as a ON = o.address_id = a.a_id
WHERE oa.delivery_status != 'Cancelled' && oa.order_status='Picked'
SELECT
orders_assigned.delivery_status AS delivery_status,
orders_assigned.username AS username,
orders_assigned.order_id AS order_id,
delboy_login.name AS del_name,
delboy_login.lat AS del_lat,
delboy_login.longi AS del_longi,
order.address_id AS address_id,
order.user_id AS user_id,
customer_login.name AS cus_name,
address.lat AS cus_lat,
address.longi AS cus_longi
FROM
orders_assigned
LEFT JOIN
delboy_login ON delboy_login.id = orders_assigned.username
LEFT JOIN
orders ON order.order_id = orders_assigned.order_id
LEFT JOIN
customer_login ON customer_login.cust_id = order.user_id
LEFT JOIN
address ON address.a_id = order.address_id
Here is the SQL you want.
Take note that you can rename the columns that the query returns as you can see from below.
delboy_login.name AS del_name,
delboy_login.lat AS del_lat,
delboy_login.longi AS del_longi,
customer_login.name AS cus_name,
address.lat AS cus_lat,
address.longi AS cus_longi
Joining table is very important, I hope that you will be able to pick up the query pattern in the future.
Best of luck to you.
EDIT:
The output you desire can be achieved by simply creating 2 different temp_arrays, and pushing them into the main array one after the other.
if ($count1 >= 1) {
while ($row = $sql->fetch()) {
$delivery_status = $row['delivery_status'];
$deliveryboy_id = $row['username'];
$order_id = $row['order_id'];
$del_name = $row['del_name'];//name
$del_lat = $row['del_lat'];//lat
$del_longi = $row['del_longi'];//long
$del_icon = $row['del_icon'];//icon
$address_id = $row['address_id'];
$user_id = $row['user_id'];
$cus_name = $row['cus_name'];//name
$cus_lat = $row['cus_lat'];//lat
$cus_longi = $row['cus_longi'];//long
$cus_icon = $row['cus_icon'];//icon
$tmp_del = array();
$tmp_del['del_lat'] = $del_lat;
$tmp_del['del_name'] = $del_name;
$tmp_del['del_longi'] = $del_longi;
$tmp_del['del_icon'] = $del_icon;
$tmp_cus = array();
$tmp_cus['cus_lat'] = $cus_lat;
$tmp_cus['cus_name'] = $cus_name;
$tmp_cus['cus_longi'] = $cus_longi;
$tmp_cus['cus_icon'] = $cus_icon;
array_push($response, $tmp_del);
array_push($response, $tmp_cus);
}
I've seen a couple variations on this, but mainly they swap the entire row rather than just one value in that row, and not dynamically.
Here's the issue:
I have three rows each with the following cells (id, title, content, display_order, visible).
id is auto_increment. title and content are manually entered and visible is a toggle. display_order is set when each row is created and automatically set as the highest integer and set at the bottom of the stack.
I set it like this so that if any of these records were to be manually deleted, i can reorder the stack automatically (if there are 4 records, and I delete #2, the new order resets as 1,2,3 and not 1,3,4).
Each row has a set of up and down arrow buttons that call move.php with queries of id(id), display_order(pos) and direction(dir).
In the move.php it uses a conditional to determine whether to move the record UP or DOWN depending on what the direction variable is set at.
What PHP code do I need to write to take these three variables (id, pos, dir) and swap the value in the table cell display_order: Here's a visual representation
Initial:
id title pos
-----------------
1 slide1 1
2 slide2 2
3 slide3 3
After I click the UP button for record ID #3:
id title pos
-----------------
1 slide1 1
2 slide2 3
3 slide3 2
MIND YOU the ID and POS will not always be the same integer
USING davidethell's suggestion I have created this:
Here's what I have created, but all I'm getting is the echo $newPos rather that is going back to the admin.php:
require ("connection.php");
$id = $_GET['id'];
$pos = $_GET['pos'];
$dir = $_GET['dir'];
if ($dir == 'up') {
$newPos = $pos-1;
} else {
$newPos = $pos+1;
}
$fromRow = "SELECT * FROM pages WHERE display_order = ".$pos."";
$toRow = "SELECT * FROM pages WHERE display_order = ".$newPos."";
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $toRow['display_order'] . " WHERE id = " . $fromRow['id']."; UPDATE pages SET display_order = " . $fromRow['display_order'] . " WHERE id = " . $toRow['id']);
if ($reord){
header("Location: admin.php");
}else{
echo $newPos;
}
The problem I'm running into is that it only echos the $newPos
UPDATED CODE:
require ("connection.php");
$fromArray = array();
$toArray = array();
$id = $_GET['id'];
$pos = $_GET['pos'];
$dir = $_GET['dir'];
if ($dir == 'up') {
$newPos = $pos-1;
} else {
$newPos = $pos+1;
}
$fromRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$pos."");
$toRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$newPos."");
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $toRow['display_order'] . " WHERE id = " . $fromRow['id']);
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $fromRow['display_order'] . " WHERE id = " . $toRow['id']);
if ($reord){
header("Location: admin.php");
}else{
echo $newPos;
}
Result: echos the $newPos instead of return to admin.php
You could use this query:
UPDATE
yourtable INNER JOIN (
SELECT
MAX(yourtable.pos) pos_prec,
curr.pos pos_curr
FROM
yourtable INNER JOIN
(SELECT pos FROM yourtable WHERE id=3) curr
ON yourtable.pos<curr.pos
GROUP BY
curr.pos) cp ON yourtable.pos IN (cp.pos_prec, cp.pos_curr)
SET
pos = CASE WHEN pos=cp.pos_curr
THEN pos_prec ELSE pos_curr END
It's a little bit complicated, but it will swap the value of the position where ID=3 with the value of the position of the preceding item, even if there are gaps.
Please see fiddle here.
EDIT
If there are no gaps, you could simply use this to move ID#3 UP:
UPDATE
yourtable INNER JOIN (SELECT pos FROM yourtable WHERE id=3) curr
ON yourtable.pos IN (curr.pos, curr.pos-1)
SET
yourtable.pos = CASE WHEN yourtable.pos=curr.pos
THEN curr.pos-1 ELSE curr.pos END;
and just use +1 instead of -1 to move down (both UP and DOWN can be combined in one single query if needed).
PHP Code
And this is using PHP and mysqli, and assuming that the position is given:
<?php
$mysqli = new mysqli("localhost", "username", "password", "test");
$pos = 3;
$dir = 'down';
if ($dir == 'up') { $newPos = $pos-1; } else { $newPos = $pos+1; }
if ($stmt = $mysqli->prepare("
UPDATE
yourtable
SET
pos = CASE WHEN yourtable.pos=?
THEN ?
ELSE ? END
WHERE
pos IN (?, ?)
AND (SELECT * FROM (
SELECT COUNT(*) FROM yourtable WHERE pos IN (?,?)) s )=2;"))
{
$stmt->bind_param("iiiiiii", $pos, $newPos, $pos, $pos, $newPos, $pos, $newPos);
$stmt->execute();
printf("%d Row affected.\n", $stmt->affected_rows);
$stmt->close();
}
$mysqli->close();
?>
(i also added a check, if trying to move UP the first pos, or DOWN the last one it will do nothing).
Assuming a $row object with each row data, just do:
if ($dir == 'up') {
$fromRow = $row2;
$toRow = $row1;
}
else {
$fromRow = $row1;
$toRow = $row2;
}
$sql = "UPDATE mytable SET pos = " . $toRow['pos'] . " WHERE id = " . $fromRow['id'];
// now execute your SQL however you want in your framework
$sql = "UPDATE mytable SET pos = " . $fromRow['pos'] . " WHERE id = " . $toRow['id'];
// now execute your SQL however you want in your framework
Put that in a function or class of some kind to make it reusable.
EDIT:
Based on your edits it looks like you are not fetching enough information in your queries. They should be:
$fromRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$pos."");
$toRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$newPos."");
You were only selecting the id field, but then you were trying to use the display_order field.
i will not write you the PHP code. But i will give you the SQL:
Let's say $delta is either +1 if the slide's position should be raised 1, or -1 if the slide's position should be lowered by 1.
$id is the id of the slide. Ow, and let's assume the table is called slides_table.
You will need 2 queries:
update slides_table set pos = pos + $delta where id = $id;
update slides_table set pos = pos - $delta where pos = (select pos from slides_table where id=$id) and id != $id
Am trying to join two tables with the same column but different values but each time i output it duplicates.
Here is my code:
<?php
$dept = $_SESSION['department'];
$dept1 = strtolower($dept);
$dept2 = str_replace(" ", "_", $dept1);
$dept4 = "$dept2" . "_200";
$dept = $_SESSION['department'];
$level = $_SESSION['level'];
$level2 = str_replace (" ", "_", $level);
if($level ="200_level") {
$query = " SELECT * FROM $dept2 Join $dept4";
}
else
{
$query = " SELCT * FROM $dept2";
}
$result = mysql_query($query) or die('<div class="header5"small_font">Your Courses are not available yet. Pls contact the ICT Unit</div>');
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$status = $row['status'];
$unit = htmlspecialchars($row['unit']);
?>
If you are looking to get the contents of two tables with the same columns, a MySQL UNION should help
UNION is used to combine the result from multiple SELECT statements into a single result set.
Like so:
$query = "(SELECT * FROM $dept2)
UNION
(SELECT * FROM $dept4)";