INNER JOIN SQL Query not working with PHP - php

I have created two tables in my database and normally my php file is able to get table data from mysql.
But when I add INNER JOIN or anything like that, it does not work anymore. No output is seen but also no error message (so the code have to be correct, I think).
Here's my php code:
<?php
$db_name = "mydatabase";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
mysqli_close($conn);
?>

Try to debug like
1.if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
2.$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
if (!$query) {
die('Invalid query: ' . mysql_error());
}

It seems there is no error in your program ! Make sure the database connection is established or not
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
The mysql query seems to be correct .. better you post your database structure ! and check the column name
firsttable.secondtable_id = secondtable.secondtable_id
in your code both are secondtable_id, is that correct column name ?

Related

second sql query based on the first one

i want to take the result of an sql query "user_id"and search using it in
in another query in another table
for example :
main query select * from tracker
second query: take the id from the first query to replace it with the name of the user found in another table "user table".
something like :
select user_name from vtiger_users where id = $row["id"]
here is my code below
<?php
$servername = "localhost";
$username = "x";
$password = "xyz";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, module, whodid,changedon FROM vtiger_modtracker_basic";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table style='float: left'><tr><th>ID</th><th>Module</th><th>Who Did</th><th>Time Of Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$user_id=$row["id"];
$username_sql="SELECT user_name FROM vtiger_users where id=".$user_id." ";
$result_username=$conn->query($username_sql);
$row2 = $result_username->fetch_assoc();
echo "<tr><td>".$row["id"]."</td><td>".$row["module"]."</td><td>".$row2["user_name"]."</td><td>".$row["changedon"]."</td></tr>";
//echo "<p>".$row2["user_name"]."</p>"
//echo $row2["user_name"];
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I guess you should use whodid column when you set $user_id = $row['whodid'] or you can use JOIN query. It will return you user_name from vtiger_users table.
SELECT
a.id,
a.module,
a.whodid,
a.changedon
b.user_name
FROM vtiger_modtracker_basic a
JOIN vtiger_users b ON a.whodid = b.id
thanks all ,that query did the job for me
SELECT vtiger_modtracker_basic.id, vtiger_modtracker_basic.module, vtiger_modtracker_basic.whodid ,vtiger_modtracker_basic.changedon ,vtiger_users.user_name FROM vtiger_modtracker_basic ,vtiger_users where vtiger_modtracker_basic.whodid = vtiger_users.id

php mysql query with multiple conditions

I need the mysql query to get the items whose nid > 910 for user_id=1 and nid > 902 for used_id <> 1.
Anybody done this? Searched but cant find it, since i am new to php and mysql.
Can't you use OR in your WHERE criteria:
SELECT *
FROM YourTable
WHERE (nid > 910 AND user_id = 1)
OR (nid > 902 AND user_id <> 1)
Try with this query:
SELECT * FROM items WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1)
SQL Query:
SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);
But if you want to call it from PHP you'll need something like this:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("exampledb",$dbhandle)
or die("Could not select exampledb");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'user_id'}." Nid:".$row{'nid'}."<br />";
}
?>

Passing form variable into Php Query

I am trying to get a variable from a form on my page 1 into a query I have made on page 2 so that when the query works it will use the variable entered on page 1
Page 1 Form
<form method="post" action="testformQ.php">
<input type="text" name="testform">
<input type="submit">enter
Page 2 Query
'$software = mysql_query("SELECT software.SoftwareID, rooms.RoomID
FROM softwareroom
INNER JOIN software
ON software.SoftwareID=softwareroom.SoftwareID
INNER JOIN rooms ON rooms.RoomID=softwareroom.RoomID
WHERE rooms.RoomNum=$_GET[testform]"); (the where clause is where i want the variable)
while($rec = mysql_fetch_array($software))
{
echo $rec['SoftwareID'] . " " . $rec['RoomID'];
}'
So where the GET testform is within the query is where I want the form variable to go.
Any help would be appreciated thanks
This code will work for you
$data = $_REQUEST['testform'];
$software = mysql_query("SELECT software.SoftwareID, rooms.RoomID
FROM softwareroom
INNER JOIN software
ON software.SoftwareID=softwareroom.SoftwareID
INNER JOIN rooms ON rooms.RoomID=softwareroom.RoomID
WHERE rooms.RoomNum='$data'");
while($rec = mysql_fetch_array($software))
{
echo $rec['SoftwareID'] . " " . $rec['RoomID'];
}'
Try this for Page02 Query..
$servername = "servername";
$username = "username";
$password = "password";
$db = "db_name";
$query = "SELECT software.SoftwareID, rooms.RoomID FROM softwareroom INNER JOIN software ON software.SoftwareID = softwareroom.SoftwareID"
+ "INNER JOIN rooms ON rooms.RoomID = softwareroom.RoomID WHERE rooms.RoomNum = '$_POST["testform"]'";
//Create db connection
$connection = mysqli_connect($servername, $username, $password, $db);
//Check connection
if(!$connection){
echo "Failed to connect to database ".mysqli_connect_error();
}
$software = mysqli_query($connection, $query);
mysqli_close($connection);

Join 3 tables to display certain data PHP-MSSQL

so i have this tables and i want to get certain datas for user to view and be able to POST to other page
i cant post images so i have to break this down so please bear with me
1st table
dbo.users
pkey(UserID)
EmployeeName
2nd table
dbo.PC
pkey(PCID)
PC_Number
3rd table
dbo.FA_PC
pkey(FAID)
fkey(UserID)
fkey(PCID)
how could i display the PC_Number of the currently selected $rs->Fields('UserID') in the same form and still be able to post it on printd.php
i dont know how to connect the dbo.users->dbo.FA_PC->dbo.PC
<form action="printd.php" method="post" target="_blank">
<?php
ini_set("display_errors","on");
$conn = new COM("ADODB.Connection");
try {
$myServer = "WTCPHFILESRV\WTCPHINV";
$myUser = "sa";
$myPass = "P#ssw0rd";
$myDB = "wtcphitinventory";
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr);
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql_exp = "select * from dbo.users";
$rs = $conn->Execute($sql_exp);
echo "<select name='empt'>";
while (!$rs->EOF) {
set_time_limit(0);
echo "<option value=".$rs->Fields('UserID')." >".$rs->Fields('EmployeeName')."</option>";
$rs->MoveNext();
}
$rs->Close();
?>
the join will look like this,
SELECT a.*, c.PC_Number
FROM users a
INNER JOIN FA_PC b
ON a.UserID = b.UserID
INNER JOIN PC c
ON b.PCID = c.PCID
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

Query on two databases on two servers not connecting

I have followed a lot of examples on this issue but I just cannot seem to get this to work.
I can query the databases individually with success, but not the two in the same query.
I've tried aliasing, referring to the servers in the query... putting `` around the names etc. Nothing works.
So this is my code
Connection strings:
/// LOCAL DATABASE
$databaseprefix = "w-";
$mysqlHost = 'localhost';
$mysqlUser = 'web123-USER1';
$mysqlPass = 'SOMEPASSWORD';
$mysqlDB = $databaseprefix . 'DATABASE1';
$conn = mysql_connect($mysqlHost,$mysqlUser,$mysqlPass,true) or die('Could not connect to SQL Server on '.$mysqlHost.' '. mysql_error());
///select remote database to work with
$localDB = mysql_select_db($mysqlDB, $conn) or die("x1 Couldn't open database $mysqlDB");
///////////// GET THE DATABASE WE WANT TO EDIT
$remoteHost = $_SESSION['localfolder'];
$remoteUser = $_SESSION['databaseuser'];
$remotePass = $_SESSION['databasepassword'];
$remoteDB = $_SESSION['database'];
$remoteconn = mysql_connect($remoteHost,$remoteUser,$remotePass,true) or die('Could not connect to SQL Server on '.$remoteHost.' '. mysql_error());
$clientDB = mysql_select_db($remoteDB, $remoteconn) or die("x2 Couldn't open database $remoteDB");
Ok then I have this
$query_string = "select
`$remoteHost`.`$remoteDB`.`pages`.`page_title`,
`$mysqlHost`.`$mysqlDB`.`c_users`.`name`
from `$remoteHost`.`$remoteDB`.`pages`
left join `$mysqlHost`.`$mysqlDB`.`c_users`
on `$remoteHost`.`$remoteDB`.`pages`.`created_by` = `$mysqlHost`.`$mysqlDB`.`c_users`.`user_id`";
echo $query_string;
//// Query the DB's
$query = mysql_query($query_string);
echo mysql_num_rows($query);
while($row = mysql_fetch_assoc($query)) {
echo $row['name'] . ' | ' . $row['page_title'];
}
The output from the Query is something like this
select `remoteaddress.co.uk`.`remote-DB`.`pages`.`page_title`,
`localhost`.`w-DATABASE1`.`c_users`.`name`
from `remoteaddress.co.uk`.`remote-DB`.`pages`
left join `localhost`.`w-DATABASE1`.`c_users` on
`remoteaddress.co.uk`.`remote-DB`.`pages`.`created_by` = `localhost`.`w-DATABASE1`.`c_users`.`user_id`
Both join fields are INT datatypes on the join and the same collation. I am not sure why this would fail. Any help would be appreciated.
That's because your local connection can't connect to remote host directly ...
You can use 2 queries, one for each server instead
$query = mysql_query($query_string, $conn);
$query = mysql_query($query_string, $remoteconn);

Categories