How to fetch data from two tables based on session variable php? - php

Actually im trying to display data from 2 tables on database based on current session, basically, i had read many article and forum on how to solve this problem but i still facing them till now. so those are data and code that already i did:
<?php
include('db.php');
$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id LIMIT 1 WHERE users.id ='$loggedin_id' " ;
$result=mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
?>
so here, i got this error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE users.id = '16'' at line 3". so if i only use this query:
$sql="SELECT* FROM users INNER JOIN details ON users.id= details.id"
it will display all data in my database, but i only need data from current session.
here is my session.php file:
<?php
include('db.php');
session_start();
$user_check=$_SESSION['sess_username'];
$ses_sql=mysqli_query($db,"select username,id from users where username='$user_check' ");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
$loggedin_id=$row['id'];
$role = $_SESSION['sess_userrole'];
if(!isset($loggedin_session) && $role!="user"){
header('Location: index.php?err=2');
}
?>
this is my tables detail:
table users
table details
hope someone can help me, im new with my sql and php. tq

Change your query like that.
$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id WHERE users.id ='$loggedin_id' LIMIT 1" ;

I think your query should be like below:
$sql = "SELECT * FROM users
INNER JOIN details ON users.id= details.id WHERE users.id = $loggedin_id ";

You can neglect the INNER JOIN and Use Procedural Steps as follows:
Step 1: Just Start Session in all your pages- session_start();
Step 2: In your Db create a column for Session e.g sessionCheck
Step 3: On the Sign-up page start session and use MySqli last insert
function like:
$_session["anything"] = mysqli_insert_id(your db connection variable);
then store this session Id to a variable (like - $sessionCheck = $_session["anything"]; Insert the value of this variable to all the column in your Database on the session column as you perform insert. Let the session column by int and unique.
Step 4: On the Display Page use control structure specifically Nested
IF instead of INNER JOIN.
STEP 5: ALL your Insertion insert the value of $_sessionCheck into
sessionCheck in all your tables except the sign-up page (because the
session id is originally picked from sign-up page so you don't need
to insert into sign up again)
Step6: All your Select should be tie to WHERE sessionCheck = $sessionCheck
This works perfectly well for me on my Procedural PHP 7 (MySqli) and MySQL 5

Related

How to use SQL NOT IN() to fetch exclusive list of records from mysql table

I'm trying to get a list of all users who have received a message (at least) from a session user while excluding those who did not.
But my code excludes only one despite there being more in this category.
Here is my code:
$SQL="select *from message where senderID="$sender"; $result=mysqli_query($link,$SQL);$totalRows=mysqli_num_rows($result);if($totalRows<>0){for($i=0;$i<$totalRows; $I){$resultData[$i]=mysqli_fetch _array($result);
}for($i=0;$i<$totalRows; $I){$receiverID=$resultData[$i]['receiver_id'];
$select="select *from users where memberID NOT IN($receiverID)";} }
Please, how do I achieve this goal?
You can do all that in one SQL query:
$SQL = "SELECT * FROM users WHERE memberID NOT IN (SELECT receiver_id FROM message WHERE senderID = '$sender')";
I have no knowledge of PHP, but you will have to consult its documentation for the correct use of for loops to retrieve the data.

get a row from a many-to-many table on MySql from both primary keys

I have two main tables:
Products
Category
Then I have a 3rd many-to-many table called Prices with the rows:
IdProducts (Primary key and Foreign Key from Products)
IdCategory (Primary key and Foreign Key from Category)
Price
The 3rd table doesn't have an individual ID for each row, just those 3 rows.
That said, I've already been able to insert data with no problems on the 3rd table using the data from Products and Category. Now I'm trying to edit this data in a small program but I just can't get if there is a coincidence to pre-fill the edit form. I'm using the following code:
$sql1 = mysqli_query($con,"SELECT * FROM table3 WHERE (idProducts='$variable1' AND idCategory='$variable2') LIMIT 1") or die(mysql_error());
$PriceCount = mysqli_num_rows($sql1);
if($productCount>0){
while($row = mysqli_fetch_array($sql1)){
$priceshow= $row["price"];
$idCategoryshow= $row["idCategory"];
$idProductshow= $row["idProduct"];
}
}
So with that I could get the price, category id, and product id ready to show in html.
I don't know if I'm doing something really wrong but my best bet is that the error is in the MySql query:
"SELECT * FROM table3 WHERE (idProduct='$variable1' AND idCategory='$variable2') LIMIT 1"
This returns no values even if I send data that I know it should be using.
Is that how I'm supposed to try to get all the rows? Or maybe something like this can't be done and I need an individual ID for the prices?
EDIT: I found a dirty work around by sending the variables on a href Link... anyway Im facing the almost very same problem when trying to update the desired row, mysql code for update is this:
"UPDATE table3 SET (price1='$var1' AND price2='$var2') WHERE (price.idProduct='$idProduct' AND price.idCategory='$idCategory') "
and i recieve the following error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET (price='123231211.00' AND price='1212654.00') WHERE (table3.idProduct='QEW21' AND ta' at line 1
Finally I can go to sleep xd
"UPDATE table3 SET price1='$var1', price2='$var2' WHERE
price.idProduct='$idProduct' AND price.idCategory='$idCategory'"
I was using "SET(X AND Y)" and "WHERE(X AND Y)" and checking the right uses of AND ends up it was actually like: "SET X, Y" and "WHERE X AND Y"

mysql query in php with more conditions from two tables

First of all, I am absolute beginner with PHP and SQL.
I have two tables: users(userID, fullname, username, email, pass, userlevel) and games(gameID, userID, club, result, created_time).
In table games I have userID, same as in table users, but it's not foreign key. When I do this query in MySQL it works fine:
DELETE FROM games
WHERE EXISTS
(SELECT * FROM users
WHERE userlevel=2
AND users.userID=games.userID)
It removes anything that users.userID matches with games.userID and if that user is userlevel 2.
I need this in PHP, but only difference would be that userID will match user's ID that is logged,and user will be able to delete only the data that is input with its userID.
Also, how to allow everyone else, with userlevel 1 to be able to delete everything in table games no matter who entered on the same submit?
I have this, but its not working....it keeps givin' me the same error:
Fatal error: Call to a member function bind_param() on a non-object in
C(...)
require ('db_con.php');
session_start();
$userID=$_SESSION["UserID"];
if (isset($_POST['delete'])){
$stmt=$con->prepare("DELETE FROM games WHERE EXISTS (SELECT FROM users AS u WHERE u.userID = ? AND u.userlevel = 2 "));
$stmt->bind_param("s",$_POST['userID']));
$stmt->execute();
}
Even if I put $userlevel=2 and replace in query u.userlevel = '$userlevel', it gives the same error...
Any suggestions would be greatly appreciated.
thanx!
userID is an integer value. Change bind_param line to
$stmt->bind_param('i', $user_id);
One reason prepare() can fail is -
if the sql statement sent to it is not valid in the current DB.
prepare() will then return false.
Eg - if the table name is not correct or one or more field in the query does not exist.
You got a bracket mismatch:
$stmt=$con->prepare("DELETE FROM games WHERE EXISTS (SELECT FROM users AS u WHERE u.userID = ? AND u.userlevel = 2 "));
should really be
$stmt=$con->prepare("DELETE FROM games WHERE EXISTS (SELECT * FROM users AS u WHERE u.userID = ? AND u.userlevel = 2 )");
Anyway, the error you received means that $con->prepare did not return an object. Most likely it returned false. I assume you are using PDO, so according to the docs:
If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
So that's the case here. Your MySQL-server was unable to bind the statement. In order to debug this better (e.g. see more helpful error messages) set PDO to throw exceptions on errors.
You could probably do it like this:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Just add that line right after you connect to the database.
i found the error, here is the wright code:
$stmt=$con->prepare("DELETE FROM games WHERE EXISTS (SELECT * FROM users WHERE users.userID = ? AND users.userlevel = 2 )");
but its not working what i wanted, it deleted all from my games table :D
i guess, SELECT * FROM has to be specific!

Doubtful about what type of JOIN on MySQL

I'm currently developing a basic web application (using MySQL and PHP). Its goal is to let me and my colleagues (and also those working in different departments) find, change and arrange work shifts. I have two tables:
Users
Shifts
Using the userId column in both tables in order to link them.
When a user looks for a different shift, the query is something like this:
SELECT
s.date,
u.lastname,
s.shift_to_give,
s.seeked_shift,
s.notes,
s.insert_date
FROM
users AS u INNER JOIN shifts AS s
ON
u.userId = s.userId
WHERE
s.shift_to_give = '$shift_to_give'
AND
(*) u.office = (
SELECT
office
FROM
users
WHERE
employee_number = '$employee_number' )
AND
(**) s.status != '1'
AND
s.date='$date'
AND
(***) s.userId != (
SELECT
userId
FROM
users
WHERE
employee_number = '$employee_number' );
The parameters I want to take care of are:.
Each user can obviously see the shifts requests pertaining to his own office (The employee number is already stored with the session from the login.
The "status" column is a flag for making out requests that have already been processed
In search mode each user doesn't see his own requests.
With this statement I have results even when I shouldn't be supposed to.
(if($r) is always true)
How could I do to make it work properly?
After this query, the code continues like so:
$result = mysqli_query($dbc,$query);
if ($result) // If there are results
{
echo "There are x records found..";
mysqli_free_result($result);
mysqli_close($dbc);
}
else
{
echo "No results :-(";
}
If I have any results with my query they are correctly displayed (by checking manually into the db) BUT it never goes to the "else" statement, even when I look for something that doesn't exist...instead, I see a blank page.
Any suggestions?
Meanwhile, thanks for replying so far :-)

Data from two tables with same column names

I have a table for users. But when a user makes any changes to their profile, I store them in a temp table until I approve them. The data then is copied over to the live table and deleted from the temp table.
What I want to achieve is that when viewing the data in the admin panel, or in the page where the user can double check before submitting, I want to write a single query that will allow me to fetch the data from both tables where the id in both equals $userid. Then I want to display them a table form, where old value appears in the left column and the new value appears in the right column.
I've found some sql solutions, but I'm not sure how to use them in php to echo the results as the columns in both have the same name.
Adding AS to a column name will allow you to alias it to a different name.
SELECT table1.name AS name1, table2.name AS name2, ...
FROM table1
INNER JOIN table2
ON ...
If you use the AS SQL keyword, you can rename a column just for that query's result.
SELECT
`member.uid`,
`member.column` AS `oldvalue`,
`edit.column` AS `newvalue`
FROM member, edit
WHERE
`member.uid` = $userId AND
`edit.uid` = $userId;
Something along those lines should work for you. Although SQL is not my strong point, so I'm pretty sure that this query would not work as is, even on a table with the correct fields and values.
Here is your required query.
Let suppose you have for example name field in two tables. Table one login and table 2 information. Now
SELECT login.name as LoginName , information.name InofName
FROM login left join information on information.user_id = login.id
Now you can use LoginName and InofName anywhere you need.
Use MySQL JOIN. And you can get all data from 2 tables in one mysql query.
SELECT * FROM `table1`
JOIN `table2` ON `table1`.`userid` = `table2`.`userid`
WHERE `table1`.`userid` = 1

Categories