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);
Related
So I have three tables I am trying to fetch data from.
A Customers table
An Orders table
and a Parts table
I am trying to basically produce a report that displays what the user bought and how much it cost. This involves getting their accountID from Customers, joining that with the accountID attached to the OrderID in Orders then taking the PartID within orders, attached to orderID, and returning the partName.
What I was thinking was looping through a php array and using sql to populate it with customerNames then use sql for the other queries to sort everything by name. Not sure if that is the best way to do that though since INNER JOIN wasn't working for me when trying to query 3 tables. Here is my code for the array:
$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON
Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);
$i = 0;
$NameArray = array();
while ($Names = $statement->fetch()) {
echo "<br>";
echo $Names[0];
$NameArray[$i];
echo "<br>";
$i++;
}
this give the error undefined index. Not really sure why
$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON
Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);
$i = 0;
$NameArray = array(); ***CREATES an empty array
while ($Names = $statement->fetch()) {
echo "<br>";
echo $Names[0];
$NameArray[$i]; ***Should start with 'echo'.
Also, there's nothing assigned to $NameArray[$i]
echo "<br>";
$i++;
}
In the above code, I found 2 issues and noted them, but neither will solve your index error. You still have to assign a value to $NameArray[$i] before you can echo it without the index error.
Regarding your loop to lookup the info, you might be able to just add the [Cost] field to your SQL like this:
SELECT Customers.firstName, Orders.Cost, Orders.PartID FROM Customers INNER JOIN Orders ON
Customers.accountID=Orders.accountID
You can subsequently add the Parts table to the query with the following join:
Orders.PartID = Parts.PartID
And then simply add Parts.partName to the SELECT fields.
I guess you are running mysqli
you will need to list all the table column for both customer and order table.
Now for testing, am adding a column name for customer and quantity for order tables.
lets assume that we want to select Customers.name and Orders.quantity from database
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
$order_quantity = $row['quantity'];
$customer_name = $row['name'];
//you can now echo
echo $customer_name.' '.$order_quantity.'<br/>';
}
?>
Now since you wants to generate an arrays, your code will look like below
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$res_arr = array();
$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
$order_quantity = $row['quantity'];
$customer_name = $row['name'];
$res_arr[] = array("customer name" =>$customer_name, "order quqntity" =>$order_quantity);
}
echo json_encode($res_arr);
exit
?>
or you can just do as per below if you do not want the resultant array response to be parameter initialized..
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$res_arr[] = $row;
}
echo json_encode($res_arr);
exit;
Actually $NameArray is an empty array.
Probable you want something like:
$NameArray[$i] = $Names[0];
and at the end of the loop you will have all the firstName(s) in $NameArray
Sorting by name can make mysql better
$sql = "select firstName
from Customers AS Customers
inner join Orders AS Orders on Customers.accountID = Orders.accountID
GROUP BY Customer.accountID
ORDER BY Customer.firstName";
...
$i=0;
while($Names=$statement->fetch()){
echo $Names[$i];
$i++;
}
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
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 ?
The purpose behind this, is for me to be able to extract data from a table thats been formed via INNER JOIN of two other tables.
I've mapped a tariff name to a username successfully. But what i want to do is to be able to return data from this new table that was created via INNER JOIN in a text field on android studio.
My main concern at the moment is figuring out the right query to do be able to return the data. I've tried researching this but have had no luck/
I have 2 databases. A useraccount database and a tariff database.
useraccount database consists of the following columns:
ID
Name
Surname
EmailAddress
PostCode
City
PhoneNumber
Username
Password
ConfirmPassword
tariffs
And my Tariff database consists of the following column:
ID
Name
I have joined the two tables using INNER JOIN, and have linked the username column with the tariff name column, essentially, i ended up with a table like this:
Username|Tariff
Here is the code for that:
$query = "SELECT useraccount.Username, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
echo "{$row->Username} ({$row->tariffs}) <br>";
}
}else{
echo "No results";
}
$query2 = "SELECT";
$result2 = mysqli_query($conn,$query2);
Question:
How do I access the columns of the result set?
This image shows the result of the execution of the PHP file
Joining two tables together does not create a third table, but creates a result set from the combined records of the two tables. In your code example, you already have access to all the data contained in the useraccounts and tariff tables. To gain access to this data, simply modify your select statement so that it references the desired columns. You could also just use the '*' wildcard to include all columns in your result set.
// Using a wildcard to get all useraccount data.
$query = "SELECT useraccount.*, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
// Reference any user data you want.
echo "{$row->Username} {$row->EmailAddress} {$row->PostCode} ({$row->tariffs}) <br>";
}
}
You need to join the user account id on the tariff id:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT useraccount.Username, tariff.Name FROM useraccount INNER JOIN tariff ON useraccount.id = tariff.id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Tarrif: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
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