I have databases called Over_Pics (with a table called "Pic" with Columns ID, PicID) and Over_SeenPics (with a table called "Seen" with Columns Text, PicID)
How do I correctly write the join function for this?
$r = mysqli_query($link, "SELECT Pic.PicID FROM Pic LEFT JOIN Seen ON Pic.PicID=Seen.PicID");
Also should the db name in mysqil_connect be left blank, since I need to access to dbs rather than 1?
I think you just need to specify the DB before the table names, like this:
$r = mysqli_query($link, "SELECT Over_Pics.Pic.PicID FROM Over_Pics.Pic LEFT JOIN Over_SeenPics.Seen ON Over_Pics.Pic.PicID=Over_SeenPics.Seen.PicID");
You can loop through the rows of the result set with this:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
foreach ($row as $key => $value){
echo $key." - ".$value.", ";
}
echo "\n";
}
That will output the results of the query to the screen. Of course you will most likely want to change the formatting.
Related
Echo out the right row from an array compiled from a mysql database.
I have extracted information from a database (locations) containing three fields: id, name, city into an array called $array. I want to loop through another database (events) in which the id's from the first database (locations) are stored in a field. When looped I want to display the corresponding name and city from the locations database.
Is this possible without having to fetch information every loop?
This is my first try
$query = "Select id, name, city FROM locations WHERE typ = '1'";
$result = mysqli_query($conn, $query);
$row = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
And then I thought I could specify the key myself like this:
$query = "Select id, name, city FROM locations WHERE typ = '1'";
$result = mysqli_query($conn, $query);
$row = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[$row['id']] = $row;
}
But I couldn't figure out how to echo the right row.
You can join both tables in a single query, using something like this:
Select locations.id, locations.name, locations.city, events.name
FROM locations
JOIN events ON locations.id = events.id
WHERE locations.typ = '1'
The events.id on the JOIN statement is assuming that this is the column name of the id in the events table. I also made the assumption that these are the two fields that will match between the two tables. Adjust accordingly if your matching criteria is different.
The SELECT statement was modified to pull columns from both tables. Add whichever fields are relevant to your needs.
I'm trying to display a HTML table with information from 3 different tables in my mysql DB. However I am unsure on how to display the information from the third table.
Currently what I am using is:
$SQL = "SELECT members.*, exp.*, lvl.*
FROM members
INNER JOIN exp ON members.id = exp.member_id
INNER JOIN lvl ON members.id = lvl.member_id
ORDER BY lvl.level DESC,
lvl.total DESC, xp.total DESC";
$result = mysql_query($SQL) or die(mysql_error());
$count = 1;
while ($row = mysql_fetch_assoc($result)) {
$level = $row['level'];
$exp = $row['exp.overall'];
}
the $level is from the second table which grabs correctly, and the $exp is what I want to grab from the third table which is "exp" but it doesn't return anything
How can I change this because at the moment it just seems to be focusing on the data from the "lvl" table when using $row[]
Edit: Both the lvl and exp tables have a row in called 'overall' which is why using $row['overall'] doesn't return what I want as it returns the data from lvl table rather than exp.
First off I believe you have a typo in your last order column: should be exp.total DESC.
Secondly, unless you specify the columns to be named with dot notation explicitly they will retain their column names so try changing the last line to:
$exp = $row['overall'];.
Also consider using mysqli or PDO.
This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.
my problem is i want to JSON_ENCODE the result of inner join query and the two columns i want to select have the same name so, the JSON object override one of them and carry only data for one column cause they have the same name,,this is my code till now.
$query = "select faculty.NAME,sector.NAME from faculty inner join sector
on faculty.SECTOR_ID=sector.ID";
$result = mysql_query($query);
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
how to do this without change the column name in the DataBase...
Try changing the output of your query:
select faculty.NAME AS facultyName,sector.NAME AS sectorName from faculty inner join sector
on faculty.SECTOR_ID=sector.ID
Using as:
select faculty.NAME as faculty_name, sector.NAME as sector_name from faculty inner join sector
on faculty.SECTOR_ID=sector.ID
This will change your json values to something like:
{"faculty_name": "first", "sector_name": "second"}
so you will need to update your javascript.
You can use ALIAS In your query so you will have different names for your columns
select faculty.NAME as faculty_name ,sector.NAME as sector_name
I want to execute a SELECT query but I don't how many columns to select.
Like:
select name, family from persons;
How can I know which columns to select?
"I am currently designing a site for the execute query by users.
So when the user executes this query, I won't know which columns selected.
But when I want to show the results and draw a table for the user I should know which columns selected."
For unknown query fields, you can just use this code.
It gives you every row fields name=>data. You can even change the key to '' to get ordered array columns by num following the columns' order in the database.
$data = array();
while($row = mysql_fetch_assoc($query))
{
foreach($row as $key => $value) {
$data[$row['id']][$key] = $value;
}
}
print_r($data);
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain.
The following query returns a result set of every column of every table in the database:
SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS;
In this sqlfiddle, it returns the following result set (truncated here for brevity):
TABLE_NAME COLUMN_NAME
-----------------------
CHARACTER_SETS CHARACTER_SET_NAME
CHARACTER_SETS DEFAULT_COLLATE_NAME
CHARACTER_SETS DESCRIPTION
CHARACTER_SETS MAXLEN
COLLATIONS COLLATION_NAME
COLLATIONS CHARACTER_SET_NAME
COLLATIONS ID
COLLATIONS IS_DEFAULT
COLLATIONS IS_COMPILED
COLLATIONS SORTLEN
Now I know that I can select the column CHARACTER_SET_NAME from the table CHARACTER_SETS like this:
SELECT CHARACTER_SET_NAME
FROM CHARACTER_SETS;
Use mysqli::query to execute these queries.
If I understand what you are asking, you probably want to use MySQLIi and the the fetch_fields method on the result set:
http://us3.php.net/manual/en/mysqli-result.fetch-fields.php
See the examples on that page.
If you want to get column names for any query in all cases it's not so easy.
In case at least one row is returned you can get columns directly from this row.
But when you want to get column names when there is no result to display table/export to CSV, you need to use PDO functions that are not 100% reliable.
// sample query - it might contain joins etc.
$query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id';
$statement = $pdo->query($query);
$data = $statement->fetchAll(PDO::FETCH_CLASS);
if (isset($data[0])) {
// there is at least one row - we can grab columns from it
$columns = array_keys((array)$data[0]);
}
else {
// there are no results - no need to use PDO functions
$nr = $statement->columnCount();
for ($i = 0; $i < $nr; ++$i) {
$columns[] = $statement->getColumnMeta($i)['name'];
}
}
Use mysql_query() and execute this query:
SHOW COLUMNS FROM table
Example:
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
use DESC table or
Example
SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table';
output
column1,column2,column3
Use fetch_fields
$sql = "SELECT * FROM AT_EMPLOYEES;";
$result = mysqli_query($conn, $sql);
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
echo $val->name ."<br>";
}