How to select values from multiple tables - mysql

I'm trying to get the row where all of the user inputs are equivalent but I'm trying to get values from multiple tables.
$query=
"SELECT *
FROM (client OR agent OR admin)
WHERE (first='".$mysqli->real_escape_string($_SESSION['first'])."'
AND last='".$mysqli->real_escape_string($_SESSION['last'])."'
AND password='".$mysqli->real_escape_string($_SESSION['pass'])."')";
is there any way to do this?

<?php
$first = $mysqli->real_escape_string($_SESSION['first']);
$last = $mysqli->real_escape_string($_SESSION['last']);
$password = $mysqli->real_escape_string($_SESSION['pass']);
$query=
"SELECT *
FROM client, agent, admin
WHERE (client.first = '$fist' AND client.last = '$last' AND client.password = '$password')
OR (agent.first = '$fist' AND agent.last = '$last' AND agent.password = '$password')
OR (admin.first = '$fist' AND admin.last = '$last' AND admin.password = '$password')";
This is the way how you could get data, but now you must check in what table data exists and for that you can use mysqli_fetch_field.
Btw, consider option to reorganize database tables, because clients, agents and admin can be stored in one table users with column type or role which represents client, agent or admin. This method is called database normalization. After that your queries and data fetching will be much simpler and faster.

Related

Select a value from table and reserve it

Low level question but, I understand that you can select elements from a table using:
$sql = "SELECT blah FROM TABLE WHERE this = 'something' ";
But when I try to select a specific value from my table, where let's say a user has no tries left so if I try to grab how many tries they have left with:
$sql = "SELECT tries FROM table WHERE user = 'something'";
How would I grab that value specifically if it was 5 or 9? I tried setting a variable equal to something I $sql off my table but it doesn't grab the value.
Edit
I have a database that has a table called Item which contains: id, name, value, and stock of a particular item. If a user wants to order that item I will first check it if's in stock with a function, to see if it is not in stock then a error message is printed, otherwise accept the order.
Extremely primitive since I'm just trying to get grab the stock value first.
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' .$query.''; //test purposes
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
echo '' .$sql2. ''; //test purposes
whats the correct way to assign the value from that specific stock to a variable?
If you want to grab rows with a set of possible values you can use 'IN' such as:
Get all columns from users table where users have 5 or 9 tries:
SELECT * FROM users WHERE tries IN('5', '9'); or
If you want to select where the user has no tries left, assuming the tries column is a numeric type you can look for rows with 0 tries:
Get all columns from Item table where stock is 0:
SELECT * FROM db_inv.Item WHERE stock = '0';
Get all columns from users table where tries is 0:
SELECT * FROM users WHERE tries = '0';
As for your php code you should be able to do the following:
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' . $query; //test purposes
$mysql_handle = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database server");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
$results = mysqli_query($mysql_handle, $sql1);
if (!empty($results) && mysqli_num_rows($results) > 0) {
while($rec = mysqli_fetch_array($results)) {
echo $rec['item_stock'];
}
}

Select from multiple sql-databases using one query

Currently I will use two queries to select data from different databases.
HereĀ“s the main sections from the code..
query from database 1
mysql_select_db("data1");
mysql_select_db("data2");
//bought databases connected
$query1 = "select * from ex.1 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run1 = mysql_query($query1);
query from database 2
$query2= " select * from ex.2 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run2 = mysql_query($query2);
Both tables in different databases will include same information from the strings "$value1" and "$value2".
I would like to combine these two strings in one query. Meaning that all information from two different databases will be selected.
I tried to use JOIN the following way:
$query = "select * from database1.ex.1 JOIN database2.ex.2 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run = mysql_query($query);
but no success..
Meaning from all this is that I would like to echo mysql-data to the same table from two different database.
while ($row=mysql_fetch_array($run)){
echo '</tr><td>'.($row['something']).'</td><td>'.($row['more']).'</td><td>'.($row['and more']).'</td><td>'.($row['and more']).'</td><td>'.($row['and something from the database2']);
This way all information should be echoed nicely, following the few strings which will found from both databases.
Is this understandable?
Instead of using mysql_* for your PHP scripts, you should use MySQLI as mysql is being deprecated.
$db = new mysqli(host, user, password, database;
You should also escape the strings to be more secure and check to see if the connection has been successful as well:
$dbhost = "xxx.xxx.xxx.xxx";
$dbuser = "xxxxxxx";
$dbpass = "xxxxxx";
$dbbase = "xxxxxx";
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbbase);
if($db->connect_errno) {
die('Could not connect to the database: ' . $db->connect_error);
}
You can follow this and repeat for multiple databases!
You have the join part right, but you have got the clause where instead of on:
$query = "SELECT * FROM database1.ex.1 as db1 JOIN database2.ex.2 as db2
ON(db1.value1='".$value1."' and db2.value2='".$value2."') order by number ASC;";
You can change db1.value1/db1.value2 for db2.whatever.

How to perform Inner joins , left joins with readbean ORM?

If I have 2 tables one is users and one is stores , the users id field is associated with the store's user_id field .
Now if I want to find all those users who has a store how can I perform it on readbean ?
and please do explain as I'm just getting started with it.
Thanks
If your queries looking complex, You can simply use plain sql inside redbean.
$records = R::getAll("SELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl1.id = tbl2.tbl1_id");
This will result into and all satisfying records array.
Here I have used R::getAll($your_qry) method, to fetch for single row use R::getRow($yoyr_sql_qry); method.
If you have any difficulties. let me know.
Is it a 1:Many or Many:Many?
If I understand what you said, it's 1:Many
DB model: stores belong to users
So, a store can belong to exactly one (1) user, correct?
If so, it's easy using redbean
$user = R::dispense('users'); // create a user
$store = R::dispense('stores'); // create a store
$store2 = R::dispense('stores'); // create a store
$store1->name = 'Foo';
$store2->name = 'Bar';
$user->xownStoresList[] = $store; // save user ( and store )
$user->xownStoresList[] = $store2; // save user ( and store )
$id = R::store( $user );
foreach ( $user->ownStoresList as $store ) {
echo $store->name . ', ';
}
// outputs: "foo, bar,"

merge multiple sql queries

In the header of the pages of my site, I have multiple SQL queries. For example:
$sql_result = mysql_query("SELECT blah2 FROM misc WHERE id='1'", $db);
$rs = mysql_fetch_array($sql_result); $blah2 = $rs[blah2];
$sql_result = mysql_query("SELECT * FROM ip_bans WHERE IP='$ip'", $db);
if (mysql_num_rows($sql_result) != 0) { header("Location: banned.php"); }
$sql_result = mysql_query("SELECT * FROM accounts WHERE username='$un' AND pw='$pw'", $db);
$rs = mysql_fetch_array($sql_result);
// do all account login check etc
$sql_result = mysql_query("SELECT * FROM members WHERE id='$id'", $db);
$rs = mysql_fetch_array($sql_result);
// get members data
..and more.
All this info is needed for each page of my site. Is there a way to combine these, or just limit the ammount of queries? I'd imagine this would get quite intensive on the database over time.
I'm not too good with JOINs and things, is that what i need?
You want to use UNION.
Here is a good tutorial: http://www.tizag.com/sqlTutorial/sqlunion.php
I would recommend you to only use it where it's "natural" and not merge to many different queries.

How to combine sql select queries for this situation?

i'm writing a chat app with php/mysql
i have 3 tables: user, room and room_participant with these structures:
user: id, username
room: id, title
room_participant: room_id, user_id
Now i want to get list of all rooms along with list of all participants in each room.
Until now i just select all rooms from room table and iterate through all rooms and select users information out of each entry, which is very inefficient.
Is there any way to combine all these select into only 1 select query?
Not certain about this without testing, but give it a try:
SELECT
room.*,
user.*
FROM room
JOIN room_participant ON room_id = room_participant.id
JOIN user ON room_participant.user_id = user.id
ORDER BY room.id
To deduplicate rooms, use GROUP_CONCAT()
UPDATE GROUP_CONCAT() modified to return id|username
SELECT
room.id, room.name
GROUP_CONCAT(CONCAT(user.id,'|',user.username)) AS userlist
FROM room
JOIN room_participant ON room_id = room_participant.id
JOIN user ON room_participant.user_id = user.id
GROUP BY room.id, room.name
ORDER BY room.id
With the userlist generated by GROUP_CONCAT as id|name,id|name,id|name you can use PHP explode() to separate them.
// Split the list on the commas
$users = explode(",", $userlist);
$final_users = array();
// Then split each on the `|`
foreach ($users as $user) {
$split_user = explode("|", $user);
// Append each as a new associative array to $final_users
$final_users[] = array('id' => $split_user[0], 'username' => $split_user[1]);
}
// Now you have an array of users as id, username
var_dump($final_users);
You may wish to do two queries, and then match things up in whatever is using MySQL, e.g. PHP.
These two:
SELECT id, title
FROM room;
SELECT rp.room_id, rp.user_id, u.username
FROM room_participant AS rp
INNER JOIN user as u ON rp.user_id = u.id;
Or these two:
SELECT id, username
FROM user;
SELECT rp.room_id, rp.user_id, r.title
FROM room_participant AS rp
INNER JOIN room as r ON rp.user_id = r.id;
Which two queries make sense depends on what you're doing with the info really.
You could go a step further and select all three separately:
SELECT *
FROM room;
SELECT *
FROM user;
SELECT *
FROM room_participant;
Note: It's probably better to state the columns, rather than using '*', just in case in the future new columns are added to the table that you're not really interested in for these queries.
Obviously, you'd then have to match everything up in whatever is using MySQL, e.g. PHP. You could create a list of rooms and users from the selected info, and then match them up with something like:
// Use MySQL to populate $roomList from database, then do...
foreach ($roomList as $room)
{
$id = $room['id'];
$title = $room['title'];
$this->roomList[$id] = new Room($id, $title);
}
// Use MySQL to populate $userList from database, then do...
foreach ($userList as $user)
{
$id = $user['id'];
$username = $user['username'];
$this->userList[$id] = new User($id, $username);
}
// Use MySQL to populate $roomParticipantList from database, then do...
foreach ($roomParticipantList as $roomParticipant)
{
$room = $this->roomList[$roomParticipant['room_id']];
$user = $this->userList[$roomParticipant['user_id']];
// You could do one/both of these, depending on requirements.
$room->enterUser($user);
$user->joinRoom($room);
}