Retrieve data from multiple tables MySQL - php

I have 2 tables: "media" and "rating"
I need to retrieve all data from both tables where "media" has a title, description and a image. "rating" only stores the media id and a vote (1 - 5).
My problem is that when i try to retrieve data and the "rating" table is empty then no data is shown and if there are more votes in the "rating" table than in the "media" table then it show duplicates of the "media".
<?php
$query = "SELECT * ";
$query .= "FROM media, rating ";
$query .= "WHERE media.id = media_fkey";
$result = mysqli_query($link, $query);
if (!$result) {
die("Database query failed.");
}
?>
I hope that this makes sense. :-)
Thank you in advance!
// René

try this
$query = "SELECT * FROM media AS m JOIN rating AS r ON m.id = r.media_fkey"
$result = mysqli_query($link, $query);
if (!$result) {
die("Database query failed.");
}
or you can use the field name with object names other than *
SELECT m.id, m.data, r.media_fkey......

Related

How to pick data from multiple db tables and inserting into one table using php and html button element

So the idea of the code below is to pick values from different db tables, which are then passed to a single db table using a html button in (approvals.php) to pass the parameter set in the code below in(accept.php).
$connect =mysqli_connect("localhost", "root", "", "projectii");
$query = "SELECT * FROM permits, sanitarypermits, mechanicalpermits, electricalpermits,
plumbingpermits, electronicspermit
WHERE
permits.Id = sanitarypermits.Id = mechanicalpermits.Id = electricalpermits.Id = plumbingpermits.Id
= electronicspermit.Id ";
$result = mysqli_query($connect, $query);
if(mysqli_query($connect, $query)){
$query = "INSERT INTO approved_permits
SELECT * FROM permits WHERE permits.Id
UNION
SELECT * FROM sanitarypermits WHERE sanitarypermits.Id
UNION
SELECT * FROM mechanicalpermits WHERE mechanicalpermits.Id
UNION
SELECT * FROM electricalpermits WHERE electricalpermits.Id
UNION
SELECT * FROM plumbingpermits WHERE plumbingpermits.Id
UNION
SELECT * FROM mechanicalpermits WHERE electronicspermit.Id ";
}
else{
echo "There is an unknown problem";
}
?>

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

Tryning to get the right information from mysql

I'm trying to call the correct mysql information.
In my first query, I check if the order is available and take the post_id so I can make a SELECT that includes all post_id's for my while.
In the first query is there many post_id's so I need to connecte tto many id's
An example that does not work but explain what I mean:
$query103 = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts`
where ID='order_id1' and ID='order_id2' and ID='order_id3'
") or die(mysqli_error($conn));
The $orderidtilsoog can be more IDs and not just 1
Hope you understand me
The is the completaly code:
$query = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_postmeta` where meta_value='$emailconvert' ORDER BY meta_id ") or die(mysqli_error($conn));
echo "Kunden er fundet og ligger på https://v1.com";
while($row55 = mysqli_fetch_array($query)) {
$orderidtilsoog = $row55['post_id']. ",";
echo $orderidtilsoog;
if(mysqli_num_rows($query) == '0') {
}else{
$query103 = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts` where ID
IN ('$orderidtilsoog') ") or die(mysqli_error($conn));
}
Just use SELECT * FROM $v1.wpd2_posts where ID IN('$orderidtilsoog')

Joining a resource and a table in php / mysql

I am relatively new to web development and I am trying to query a MySQL database with a database through the following commands, however I unable to do so and I am getting the following as error:
PHP Code:
$query1 = "SELECT id_2 FROM idTable WHERE id = '$idno'";
$result1 = mysql_query($query1);
if (!$result1)
die("Database access failed(error 7): " . mysql_error());
/************ possible error point *******************/
$query2 = "SELECT * FROM Data NATURAL JOIN $result1 LIMIT $num,$last_num";
$result = mysql_query($query2);
if (!$result)
die("Database access failed(error 8): " . mysql_error());
Error:
Database access failed(error 8): Table 'Database.Resource' doesn't exist
Basically I have two tables. I need to choose some values from the 'id_2' column of idTable and depending upon the values chosen, I want to pick all the rows from the table 'Data' that match the corresponding ids by performing a join operation. Can anybody please tell me how to achieve the join of the resource returned and the table (Or in general, how do I solve my problem)?
SELECT d.*
FROM Data d
JOIN idtable i
ON i.id2 = d.id
WHERE i.id = $idno
ORDER
BY d.id
LIMIT $num,$last_num;
I am still not sure what is relations between these 2 tables but valid code and query should be something like :
$query1 = "SELECT * FROM Data
INNER JOIN idtable
ON idtable.id = Data.id_2
AND idtable.id = $idno
LIMIT $num,$last_num";
$result = mysql_query($query1);
if (!$result)
die("Database access failed : " . mysql_error());
But valid is not equal correct or good :-)
And once I've reread my own query, I have the same question as #Strawberry: why do we need join? why not just:
$query1 = "SELECT * FROM Data
WHERE Data.id_2 = $idno
LIMIT $num,$last_num";
$result = mysql_query($query1);
if (!$result)
die("Database access failed : " . mysql_error());

'Counting' the number of records that match a certain criteria and displaying the numbers (using PHP and MySQL)

I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.

Categories