I am trying something here, I want to make a condition that allows me to fetch an info from a row in a Mysql if the page title is the same with a value from table "names"/column "lastname". Here I had made a table "names"
The "firstname" column would be unique in this table.
+---------+-----------+----------+
| id | firstname | lastname |
+---------+-----------+----------+
| 1 | John | Smith |
| 2 | Jane | Smith |
| 3 | Jimbo | Jones |
| 4 | Andy | Smith |
| 7 | Chris | Jones |
| 45 | Anna | Bell |
| 44 | Jimmy | Carr |
| 43 | Albert | Smith |
| 47 | Johnna | Doe |
+---------+-----------+----------+
If the page name is equal to "Jimbo" than display "Jones" else error text (but still showing) or so. I don't know if this way good is while I don't have any ideeas anymore.
The code that i am using so far:
<?php echo get_the_title($ID); ?>
- for fetching the title -
<?php
$result = mysql_query("SELECT lastname FROM names WHERE id = '2'");
if (!$result) {
echo 'error:bla ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 2
echo $row[1]; //
?>
For fetching the row -
In Wordpress I am using PHP code for posts and pages (I can make a shortcode).
http://codex.wordpress.org/Class_Reference/wpdb
global $wpdb;
$result = $wpdb->get_row("SELECT * FROM names WHERE id='2' ");
if($result){
echo $result->lastname;
}
Related
This question already has answers here:
How to join two tables mysql?
(4 answers)
Closed 2 years ago.
I have two tables that looks something like this (made as example):
Table sales:
| ID | date | displayname | status |
| 1 | 2020/08/03 16:25:26 | Angel | OK |
| 2 | 2020/08/03 16:25:26 | Angel | OK |
| 3 | 2020/08/03 16:25:26 | Cabil | X |
| 4 | 2020/08/03 16:25:26 | Syed | OK |
...
Table users (all of the columns has value, but removed for GDPR reasons):
| ID | displayname | fullname | email |
| 1 | Angel | | |
| 2 | Nico | | |
| 3 | Raquie | | |
| 4 | Cabil | | |
| 5 | Syed | | |
...
I have a PHP script that looks like this:
<?php
$query = "SELECT * FROM sales WHERE status='OK' ORDER BY STR_TO_DATE(`date`, '%Y/%m/%d %H:%i:%s') DESC LIMIT 5";
if ($result = $link->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
echo '<div class="my-box">';
echo "{$row['id']}";
echo "{$row['date']}";
echo "{$row['dbirth']}";
echo "{$row['email']}";
echo "{$row['displayname']}";
echo '</div>';
}
$result->free();
}
?>
Now it currently displays each displayname for each sale in echo "{$row['displayname']}";, but insted of the displayname, I want to show the fullname for the user that has the current display name. How can I accomplish this?
You seem to be looking for a join:
select s.*, u.fullname
from sales s
inner join users u on u.displayname = u.displayname
I have two tables in my mySQL database:
table "animals":
| animal | name |
|:-----------|------------:|
| cat | Tom |
| dog | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
At first I select from the table "orders" the following data:
<?php
$pdo = Database::connect();
$sql = 'SELECT * FROM orders ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo ('<td>a:'.$row['id'].'</td>');
echo ('<td>b:'.$row['animal'].'</td>');
echo ('<td>c:'.$row['animal'].'</td>');
}
Database::disconnect();
?>
Now I want to check if in my mySQL table "animal" the animal has a name. If yes print at position b the name. If there is no name print the animal:
| a:1 | b:Tom | c:cat |
| a:2 | b:dog | c:dog |
Thank you for your answers! I tried to work now with the answer of Jayo2k. I need to do a little change in my question, I found out I did a little mistake. So here I try to describe what I need as specific as possible:
table "animals":
| name | animal |
|:-----------|------------:|
| Tom | cat |
| Jerry | dog |
| Alfred | duck |
| Sam | |
| Donald | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
| 3 | duck |
| 4 | frog |
| 5 | pig |
With the following code from Jayo2k...
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM animals, orders WHERE orders.animal = animals.animal";
foreach ($pdo->query($sql) as $row) {
echo '<tr> ';
echo('<td>a:'.$row['id'].' </td>');
echo('<td>a:'.$row['animal'].' </td>');
echo('<td>b:'.$row['name'].' </td>');
echo '</tr> ';
}
Database::disconnect();
?>
... I get this result:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
But what I need is:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
| a:4 | b:frog | c:frog |
| a:5 | b:pig | c:pig |
You can use LEFT JOIN, and use the IF condition to check the value is not empty, along with IFNULL, that will make null values in columns to blank.
SELECT O.id, IF(IFNULL(A.name, '') = '', A.animal, A.name) name, A.animal
FROM orders O
LEFT JOIN animals A
ON O.animal = A.animal
ORDER BY O.id DESC
What I do is (I am using PDO):
SELECT * FROM animal, orders WHERE orders.animal = animals.animal
It will select both animals and orders table and joint the animal row from orders with the animal row from animal.
you should get an array like this
[0] =>
id = 1
name = tom
animal = cat
[1] =>
id = 2
name =
animal = dog
Now up to you to do all the modification you want
I'm very new to php and database programs but trying to learn the language and develop a system for my library. I have a database called booksdb and two tables called "books" which contains titles of books and author and bookcatname which contains categories of books with a unique Category ID.
What I want to do is, display all categories on the page and when one category link is clicked, I want to see the names of books and authors under that particular category displayed on another page,
Example:
Art;
Color and Light by James Gurney
The Art Spirit by Robert Henry
How Pictures Work by David Bayles
Imaginative Realism by James Gurney
Here is my code but it does not work.
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connedt to the Database' .mysql_errno());
mysql_select_db("booksdb");
//$res = "SELECT * FROM bookstable GROUP BY category ORDER BY category ASC";
$res = "SELECT * FROM bookcatname ORDER BY category ASC";
$res_query = mysql_query($res) or die (mysql_error());
$ra = mysql_fetch_assoc($res_query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select a Company</title>
</head>
<body>
<?php do { ?>
<p><?php echo $ra['category']; ?></p>
<?php } while ($ra = mysql_fetch_assoc($res_query))?>
</body>
</html>
1.Table name - bookcatname
+----+--------+----------+
| id | cat_id | category |
+----+--------+----------+
| 1 | 1 | Art |
| 2 | 2 | Drama |
| 3 | 3 | Music |
| 4 | 4 | Fiction |
| 5 | 5 | Computer |
+----+--------+----------+
2.Table name - books
+----+--------+---------------------------------+-----------------------+
| id | cat_id | title | author |
+----+--------+---------------------------------+-----------------------+
| 1 | 1 | Color and Light | James Gurney |
| 2 | 1 | The Art Spirit | Robert Henry |
| 3 | 1 | Art & Fear | David Bayles |
| 4 | 1 | How Pictures Work | Molly Bang |
| 5 | 1 | Imaginative Realism | James Gurney |
| 6 | 2 | A Walk To Remember | Nicholas Sparks |
| 7 | 2 | An Old Fashioned Girl | Louisa May Alcott |
| 8 | 3 | The Rest Is Noise | Alex Ross |
| 9 | 3 | It Still Moves | Amanda Petrusich |
| 10 | 3 | Chronicles | Bob Dylan |
| 11 | 3 | Dream Boogie | Peter Guralnick |
| 12 | 3 | Escaping The Delta | Robert Johnson |
| 13 | 4 | Atlas Shrugged | Ayn Rand |
| 14 | 4 | Anthem | Ayn Rand |
| 15 | 4 | Sons and Lovers | D.H. Lawrence |
| 16 | 4 | Henderson the Rain King | Saul Bellow |
| 17 | 5 | The Art of Computer Programming | Donald Knuth |
| 18 | 5 | The Art of Unix Programming | Eric Raymond |
| 19 | 5 | Free Software, Free Society | Richard M. Stallman |
| 20 | 5 | Database System Concepts | Abraham Silberschatz |
| 21 | 5 | 3ds Max 2008 in Simple Steps | Kognet Solutions Inc. |
+----+--------+---------------------------------+-----------------------+
Your current code to show categories don't work cause your using :
$ra = mysql_fetch_assoc($res_query);
and after you do it again in a loop :
while ($ra = mysql_fetch_assoc($res_query)
Do only one while() to get categories :
$getCategories = mysql_query("SELECT * FROM bookcatname ORDER BY category ASC");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'';
}
Now, you will need another page to get books from this category (or you can do it in same page).
books.php
// Same stuff here to connect database
// you check if a category is sent, else you redirect to categories page.
if ( empty($_GET['cat_id']) )
{
header('Location: index.php');
exit();
}
// Now you get books from category
// intval() convert to number
$getBooks = mysql_query("SELECT * FROM books WHERE cat_id = '".intval($_GET['cat_id'])."'");
echo '<ul>';
while ( $book = mysql_fetch_assoc($getBooks) )
{
echo '<li>'.$book['title'].' by '.$book['author'].'</li>';
}
echo '</ul>';
Hello I have actually asked a similar question a while ago but only just realized I did not get an answer that solves my problem.
I have 2 tables in a MySQL DB, that are connected by the same main id, the following code is just a simplified example of the original code:
table1:
+-----------------------+
| main_id | name | type |
+-----------------------+
table2:
+----------------------------------------+
| main_id | secondary_id | color | price |
+----------------------------------------+
the result I want to achieve is to get every row of table 1, and under each one list all the linked by main id rows from table2, for example:
table1 rows:
+-------------------+
| 1 | name1 | type1 |
| 2 | name2 | type2 |
| 3 | name3 | type3 |
+-------------------+
table2 rows:
+----+------+----------+------+
| 1 | 23 | red | 500 |
| 1 | 24 | blue | 600 |
| 1 | 25 | green | 700 |
| 2 | 26 | pink | 400 |
| 2 | 27 | purple | 200 |
| 3 | 28 | white | 100 |
+----+------+----------+------+
result in display:
<h1 class="1">name1, type1</h1>
<div class="23">red,500</div>
<div class="23">red,500</div>
<div class="24">green,700</div>
<h1 class="2">name2, type2</h1>
<div class="25">pink,400</div>
<div class="26">purple,200</div>
And so on...I was using a while loop inside a while loop which wasn't giving me the required result, then I was advised to use MySQL JOIN, but when I do I get all values of the matching ids and cant display the headings only once and then list the related results under it, can someone please help me?
this is a simplified query i was using:
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
//Get details and display
}
}
}
In your description, you use main_id, but in the code you use just id. Not sure which you're really using here - you will have to edit the code below to match your actual column names. If the database column name is actually main_id, then for instance the line with $id = $rows['id'] would have to be $rows['main_id']. Or it won't work.
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
echo '<h1 class="'.$rows['id'].'">'.$rows['name1'].', '.$rows['type'].'</h1>';
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
if ($row2['id'] == $id) {
echo '<div class="'.$row2['secondary_id'].'">'.$row2['color'].', '.$row2['price'].'</div>';
}
}//while
}//else
}//while
I'm having a hard time organizing the data that I get from mysql_fetch_array().
I have a DB table with that looks something like this:
+---------------------+------------------+---------------+--------+---------+
| date | name | indexed_pages | nameID | entryID |
+---------------------+------------------+---------------+--------+---------+
| 2012-06-15 21:18:06 | site1.com | 200 | 1 | 1 |
| 2012-06-15 21:18:10 | site2.com | 25 | 2 | 1 |
| 2012-06-15 21:18:13 | site3.com | 12 | 3 | 1 |
| 2012-06-15 21:18:16 | site4.com | 8 | 4 | 1 |
| 2012-06-15 21:18:19 | site5.com | 2 | 5 | 1 |
| 2012-06-16 00:11:12 | site1.com | 191 | 1 | 2 |
| 2012-06-16 00:11:21 | site2.com | 25 | 2 | 2 |
| 2012-06-16 00:11:30 | site3.com | 12 | 3 | 2 |
| 2012-06-16 00:11:44 | site4.com | 8 | 4 | 2 |
| 2012-06-16 00:11:51 | site5.com | 2 | 5 | 2 |
| 2012-06-18 10:20:47 | site1.com | 191 | 1 | 3 |
| 2012-06-18 10:20:52 | site2.com | 25 | 2 | 3 |
| 2012-06-18 10:20:56 | site3.com | 12 | 3 | 3 |
| 2012-06-18 10:21:00 | site4.com | 8 | 4 | 3 |
| 2012-06-18 10:21:04 | site5.com | 2 | 5 | 3 |
+---------------------+------------------+---------------+--------+---------+
I need to order the results in a Google Line Graph in the following manner:
['date', 'site1_entryID=1', 'site2_entryID=2', 'site3_entryID=3', (...)],";
The thing is that I'm having trouble managing the arrays that I generate. I'm using the following code:
mysql_connect("host_here", "username_here", "pass_here") or die(mysql_error());
mysql_select_db("my_database") or die(mysql_error());
$query = "SELECT * FROM pages";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
After this I need to echo the number of indexed_pages for each site where entryID = 1.
I don't know if this description is confusing or not, but I've tried pretty much everything and can't get the organize the data from the arrays to serve what I need to do. Help, please!
Thanks in advance!
Don't use select *, that's lazy, and you're stuck accepting the fields in the order the DB decides to produce them in.
Specify the fields you want, in the order you want:
SELECT date, name, indexed_pages, etc...
I think the simplest query is :
$result= mysql_query("SELECT name, index_pages, entryID from table_name WHERE entryID =
1");
while($row=mysql_fetch_array($result)){
echo "$row[name]";
echo "$row[index_pages]";
echo "$row[entryID]";
}
Try this. There might be some mistakes. Because i developed it fast. And replace table_name with yours.
Or you can display it in a table:
echo "<table>";
echo "<tr><td>Sit Name</td>";
echo "<td>Page Name</td>";
echo "<td>EntryID</td>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>$row[name]</td>";
echo "<td>$row[index_pages]</td>";
echo "<td>$row[entryID]</td>";
echo "</tr>";
}
echo "</table>";
SELECT date, name, indexed_pages
FROM pages
where entryID=1
order by date asc ,name asc
Not sure if this will help
mysql_connect("host_here", "username_here", "pass_here") or die(mysql_error());
mysql_select_db("my_database") or die(mysql_error());
$query = "SELECT * FROM pages";
$result = mysql_query($query);
$data[]='date';
while($row = mysql_fetch_assoc($result)){
$name=substr($row['name'], -4);
$data[]= $name."_entryID=".$row['entryID'];
}
A little of a brute force method.