<?php
$hostdb = "localhost";
$userdb = "root";
$passdb = "";
$namedb = "dctdb3";
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
$query = "SELECT msdnd_oct.id as id1, msakl_oct.id as id2, msdnd_oct.sold as sold1, msakl_oct.sold as sold2, msdnd_oct.sales as sales1, msakl_oct.sales as sales2 FROM msdnd_oct inner join msakl_oct ON msakl_oct.id=msdnd_oct.id";
?>
The code above is the only thing I have found from searches but it's not what i'm looking for.
Hi there I have been searching for awhile but cannot find what I'm looking for.
I have two tables named "msdnd_oct" and "msakl_oct".
They are both basically monthly summaries.
I want to make a comparison between the two tables. Display both tables together. So that I can see which table has more 'sold' items. So for example, if the table 'msdnd_oct' has 40 'sold' and 'msakl_oct' has 39. I can see that dnd has more.
The three rows that I want to display is 'id', 'sold' and 'sales'
Thank you for your help!
If I understood you correctly, you want something like this.
"SELECT
msdnd_oct.id as id1,
msakl_oct.id as id2,
msdnd_oct.sold as sold1,
msakl_oct.sold as sold2,
msdnd_oct.sales as sales1,
msakl_oct.sales as sales2
FROM msdnd_oct inner join msakl_oct ON msakl_oct.id=msdnd_oct.id"
If you want to compare total sales, or sold items you can use GROUP BY
Or If you simply want to combine to tables without joining them you can use UNION
You can execute above query in php as below
$query = "SELECT
msdnd_oct.id as id1,
msakl_oct.id as id2,
msdnd_oct.sold as sold1,
msakl_oct.sold as sold2,
msdnd_oct.sales as sales1,
msakl_oct.sales as sales2
FROM msdnd_oct inner join msakl_oct ON msakl_oct.id=msdnd_oct.id";
$result = mysqli_query($dbhandle,$query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id1: " . $row["id"]. " - id2: " . $row["id2"]. " <br>";
}
} else {
echo "0 results";
}
$conn->close();
I encourage you learn much more about connecting to Mysql, retrieving data from Mysql with PHP. Take a look at below links. Then you will get the clear idea of how to do your given task.
Learn about Php & Mysql
Learn about GROUP BY statement
Learn ab obout UNION operator
Related
I tried to execute the query, but the result was null, I executed the same query in PhpMyAdmin and returns the result.
The problem is when the query contains SELECT inside another SELECT statement (imbricate), so when the query contains only one SELECT statement, it works fine and returns the result. Here is the code:
db_config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "university_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
get_planning.php
<?php
require 'db_config.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cours.jour,
TIME_FORMAT(cours.heure_debut, '%H:%i') AS debut,
TIME_FORMAT(cours.heure_fin, '%H:%i') AS fin,
enseignant.nom_ens as prof, modules.nom_mod as module, salles.nom_salle as salle
FROM cours, promotion, enseignant, modules, salles
WHERE cours.id_promo = (SELECT id_promo FROM promotion WHERE promotion.niveau = '2'
AND promotion.id_speci = (SELECT id_speci FROM spécialité WHERE nom_speci = 'MGL'))
AND cours.id_promo = promotion.id_promo AND cours.id_ens = enseignant.id_ens AND cours.id_salle = salles.id_salle AND cours.id_mod = modules.id_mod
ORDER BY cours.id_cours;";
$result = $conn->query($sql);
if($result == null)
echo "Result is empty!";
Output:
Result is empty!
Information:
PHP: Version 7.3.5
Database: MySQL
Three suggestions for troubleshooting this problem:
Change your cours.id_promo = (SELECT ... to cours.id_promo IN (SELECT... and do the same to the line after it. Why? if you use = and the inner select statement returns more than one result, boom. Query fails. SQL is, at its heart, a set-processing language, and this IN that checks that this is a member of the set that.
echo your $sql value to make sure the statement in it is correct. Try running the exact statement via phpmyadmin to make sure it gives you what you expect.
You have this
if($result == null)
echo "Result is empty!";
Change it to this
if(!$result)
echo 'sql failure:', $conn->error, ': ', $sql;
The query() method only returns a falsey result if the query failed. If it succeeds but finds no matching rows, query() returns an empty result set. So anytime your $result is falsey, you made a programming error in your query. The echo I mentioned will diagnose it for you.
Pro tip Always check SQL operations for errors.
Pro tip 2. Bring your SQL skills into the 21st century. Use explicit join operations rather than old-timey comma-join operations. Change ...
SELECT cours.jour, whatever, whatever
FROM cours
JOIN promotion ON cours.id_promo = promotion.id_promo
JOIN enseignant ON cours.id_ens = enseignant.id_en
JOIN modules ON cours.id_mod = modules.id_mod
JOIN salles ON cours.id_salle = salles.id_salle
WHERE cours.id_promo IN (SELECT id_promo FROM promotion WHERE promotion.niveau = '2')
AND promotion.id_speci IN (SELECT id_speci FROM spécialité WHERE nom_speci = 'MGL')
ORDER BY cours.id_cours
The relationships between your tables are much easier to read and understand this way. And, you can change JOIN to LEFT JOIN if your application requires it.
Just a suggestion.
Instead of nested old implicit join syntax based list table, where clause and nested sub-query should use explicit join syntax.
SELECT cours.jour
, TIME_FORMAT(cours.heure_debut, '%H:%i') AS debut
, TIME_FORMAT(cours.heure_fin, '%H:%i') AS fin
, enseignant.nom_ens as prof
, modules.nom_mod as module
, salles.nom_salle as salle
FROM cours
INNER JOIN promotion ON cours.id_promo = promotion.id_promo
AND promotion.niveau = '2'
INNER JOIN enseignant ON cours.id_ens = enseignant.id_ens
INNER JOIN modules cours.id_mod = modules.id_mod
INNER JOIN salles ON cours.id_salle = salles.id_salle
ORDER BY cours.id_cours;
I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}
I am requesting your advice about the following:
I have two tables:
Customers and Orders.
I am printing the data of customers inside a table using a while loop:
$sql = "SELECT * FROM wccrm_customers where status = '1' order by date desc";
$result = mysql_query($sql, $db);
while ($daten = mysql_fetch_array($result)) { ?>
echo $daten[id];
echo $daten[name] . ' ' . $daten[vorname];
echo $daten[email];
echo $daten[telefon];
} ?>
Now I try to add a new field in this list: Purchased YES/NO. As we have more customers then buyers, we want to show whether someone has bought or not:
The Connection between this two tables is the first/lastname in both tables!
So if customer.name = orders.name and customer.firstname = orders.firstname I want to echo "YES" if not then "NO"
I tried with a JOIN, but here I just get the results who are in both table:
SELECT *
FROM wccrm_customers AS k
INNER JOIN wccrm_orders AS o
ON o.namee = k.name AND o.firstname = k.firstname
but I need to have all of the customers and the ones who are in both lists marked...
Is this possible? If yes: How can I achieve this?
Thank's for your advice!
Kind regards,
Stefan
This has nothing to do with PHP, or with while loops; you just need to form your join properly:
SELECT DISTINCT
`k`.*,
`o`.`namee` IS NOT NULL AS `Purchased`
FROM `wccrm_customers` AS `k`
LEFT JOIN `wccrm_orders` AS `o`
ON
`o`.`namee` = `k`.`name`
AND `o`.`firstname` = `k`.`firstname`
Read more about the different join types: http://www.sql-join.com/sql-join-types/
(images courtesy of that site, which also contains an example and discussion of almost exactly what you're trying to do!)
By the way, you must have missed the massive red warning banner in the manual about using the deprecated (now removed) mysql_* functions. You should stop doing that! Use MySQLi or PDO instead.
a shorter one
SELECT DISTINCT k.*, IF(o.namee IS NULL, 'no', 'yes') purchased
FROM
wccrm_customers AS k
LEFT JOIN wccrm_orders AS o USING (namee,firstname)
Hi guys in the code below you can see what my JSON returns.
{"lifehacks":[{
"id":"2",
"URLtoImage":"http:\/\/images.visitcanberra.com.au\/images\/canberra_hero_image.jpg",
"title":"dit is nog een test",
"author":"1232123",
"score":"2",
"steps":"fdaddaadadafdaaddadaaddaadaaaaaaaaaaa","category":"Category_2"}]}
What the JSON returns is fine. The only problem is it is only displaying lifehacks if it has one like or more. So what should I change about my Query so it would display lifehacks without likes aswell.
//Select the Database
mysql_select_db("admin_nakeitez",$db);
//Replace * in the query with the column names.
$result = mysql_query("select idLifehack, urlToImage, title, Lifehack.Users_fbId, idLifehack, steps, Categorie, count(Lifehack_idLifehack) as likes from Lifehack, Likes where idLifehack = Lifehack_idLifehack AND idLifehack > " . $_GET["id"]. " group by idLifehack;", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['idLifehack'];
$row_array['URLtoImage'] = $row['urlToImage'];
$row_array['title'] = $row['title'];
$row_array['author'] = $row['Users_fbId'];
$row_array['score'] = $row['likes'];
$row_array['steps'] = $row['steps'];
$row_array['category'] = $row['Categorie'];
//push the values in the array
array_push($json_response,$row_array);
}
echo "{\"lifehacks\":";
echo json_encode($json_response);
echo "}";
//Close the database connection
fclose($db);
I hope my problem is clear like this. Thank you in advance I can't figure it out myself.
You need a LEFT JOIN here. Your query has an INNER JOIN.
select
idLifehack,
urlToImage,
title,
Lifehack.Users_fbId,
idLifehack,
steps,
Categorie,
count(Lifehack_idLifehack) as likes
from Lifehack
left join Likes on idLifehack = Lifehack_idLifehack
where idLifehack > whatever
group by idLifehack;
There's an excellent explanation of the different join types here.
A couple additional points...
Use prepared statements in your PHP. Your code is wide-open to SQL Injection, which has ruined careers and led to millions of innocent people having their personal information stolen. There are plenty of web sites showing how to do this so I won't go into it here, though I'll say my favorite is bobby-tables.
Avoid the implicit join anti-pattern in your queries. This is an implicit join:
FROM a, b
WHERE a.id = b.id
Use explicit joins instead; they separate your join logic from your filtering (WHERE) logic:
FROM a
INNER JOIN b ON a.id = b.id
I have a couple of tables that i feel different data inside based on user inputs, the tables contain different columns, so i want to create like a page something like user activity to show him/her everything what he was doing, now i have a couple of tables that hold data and i need somehow to select all the data based on one account number that all the tables contain it and display to the user based on the date, what i had until now is below:
global $wpdb;
global $userInfo;
$il_wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
This example with 2 tables only, but i have around 6 tables that i need to join them
$_IL_TABLE_NAME = $wpdb->prefix . "il_complaints";
$_IL_TABLE_NAME1 = $wpdb->prefix . "il_internal_transfer";
$_IL_GET_COOKIES_VAL = $userInfo['account'];
//my query
$_IL_QUERY_RESULT = $il_wpdb->get_results( "SELECT $_IL_TABLE_NAME.il_date, $_IL_TABLE_NAME1.il_amount FROM $_IL_TABLE_NAME, $_IL_TABLE_NAME1 WHERE $_IL_TABLE_NAME.il_mt4_account='$_IL_GET_COOKIES_VAL' ");
//display data
foreach($_IL_QUERY_RESULT as $_IL_ROW){
echo $_IL_ROW->il_date;
echo $_IL_ROW->il_amount;
}
Because data will be displaed here from multiple tables how i can put to them something first raw is coming from first table and put to it table 1, the second row is coming from second table and to put to it table 2, to show to the user what he/she did and from where
I will appreciate any help.
try based on comments
$_IL_QUERY_RESULT = $il_wpdb->get_results( "
SELECT pr_il_complaints.il_date, pr_il_internal_transfer.il_amount
FROM pr_il_complaints t1 INNER JOIN pr_il_internal_transfer t2 ON t1.il_from_mt4 = t2.il_mt4_account;
");
You need a SQL JOIN, like this:
SELECT t1.name, t2.salary
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;
SELECT t1.name, t2.salary
FROM employee t1 INNER JOIN info t2 ON t1.name = t2.name;
More: http://dev.mysql.com/doc/refman/5.0/en/join.html
try this...
$mysqli = new mysqli("localhost", "username", "password", "database");
$strr = "SELECT * FROM table1
INNER JOIN tabel2
ON table2.account_number = '".$something."'
INNER JOIN tabel3
ON table3.account_number = '".$something."'
";
$result = $mysqli->query($strr);
while($arr = $result->fetch_array())
{
echo "<pre>"; print_r($arr); echo "</pre>";
}
You need to use joins
SELECT TN.il_date, TN2.il_amount , TNX.field...
FROM $_IL_TABLE_NAME TN
JOIN $_IL_TABLE_NAME1 T2 ON TN.ID_FIELD = TN2.ID_FIELD
JOIN $_IL_TABLE_NAMEX TX ON TX.ID_FIELD = DATABASE.FIELD
JOIN ...
WHERE $_IL_TABLE_NAME.il_mt4_account='$_IL_GET_COOKIES_VAL'
Extra Information:
1.-Sintaxis de JOIN
2.-Understanding JOINs in MySQL and Other Relational Databases