Passing value from SQL query to another SQL query in php - php

I want to use a variable that comes from a table i MySQL and pass it to Another SQL-Query with PHP. Can´t get it to work and I can´t find out why.
Here is the code:
<html>
<head><title></title></head>
<body>
<div>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='$blogs_profile_id' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
</div>
</body>
</html>
it says the variable is undefined. How can I define it and pass the value when the a href-link is clicked?

Error is clear. Undefined variable:
You didn't defined this variable anywhere
before select statement
$blogs_profile_id
I think you need to add this variable in query string and get from $_GET.
UPDATE 1:
You have following issues in your code.
Missing blog_profile_id in your query string.
Undefined variable means you are using a variable but didn't defined.
Using mysql_* extension its deprecated
Solution:
Replace this:
echo 'Choose blogwriter';
With:
echo 'Choose blogwriter';
And than use that:
if (intval($_GET['blog_id']) > 0)
{
$blogs_profile_id = intval( $_GET['blog_id']);
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date FROM blog INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID WHERE blog.BlogID=".$blogs_profile_id." ORDER BY blogpost.Date DESC")
or die(mysql_error());
.....

Change the order of your queries. The second query code has to be coming first in order as below
<html>
<head><title></title></head>
<body>
<div>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='"+$blogs_profile_id+"' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
</div>
</body>
</html>

Related

Echo issue with while / if / else

I am a beginner learning PHP and MySQL and have gotten to chapter 5 of Head First PHP & MySQL and am attempting a self made project in which I created a database and a index.php page where I can see the results printed out. When I go to my index.php page I see the HTML title but the PHP code is not printing out my submissions. I have to assume my code syntax is correct or I would end up with a blank page. Can someone please tell me what I have coded wrong to wind up with no output?
<?php
$dbc = mysqli_connect(localhost, root, root, itmyfamily);
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
$data = mysqli_query($dbc, $query);
$i = 0;
while ($row = mysqli_fetch_array($data))
{
if ($i == 0)
{
echo '<strong>First Name:</strong> ' . $row['first_name'] . ' <br />';
echo '<strong>Last Name:</strong> ' . $row['last_name'] . ' <br />';
echo '<strong>Spouse Name:</strong> ' . $row['spouse_name'] . ' <br />';
echo '<strong>Email:</strong> ' . $row['email'] . ' <br />';
}
else
{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
Set this on top of the source code to display errors.
<?php error_reporting( E_ALL ); ?>
Or set display_erros in php.ini as follows:
display_errors = On
error_reporting = E_ALL | E_STRICT
Also try to replace your source code with following,
<?php
//Establish connection with database
$dbc = mysqli_connect(localhost,root,root,itmyfamily);
//Order the data to be retrieved
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
//Execute the connect command and the query
$data = mysqli_query($dbc,$query);
while ($row = mysqli_fetch_array($data)) {
//Loop through the array of family submissions, formatting it as html
$i = 0;
//Display family submissions
if ($i == 0) {
echo '<strong>First Name:</strong> ' .$row['first_name']. ' <br />';
echo '<strong>Last Name:</strong> ' .$row['last_name']. ' <br />';
echo '<strong>Spouse Name:</strong> ' .$row['spouse_name']. ' <br />';
echo '<strong>Email:</strong> ' .$row['email']. ' <br />';
}
else{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
?>
If you can write it this way, I think you don't even need the $i.
$result = mysql_query("SELECT id, first_name FROM mytable");
if($result){
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["first_name"]);
}
}
else
echo 'There is no info in the database';
Read here for more information about PHP mysql_fetch_array http://www.php.net/mysql_fetch_array
Read here for more information about iterations. http://webcheatsheet.com/php/loops.php
Please note that the method you have used is deprecated from PHP 5.5.0. So I suggest you consider mysqli or PDO. Examples can be found in below PHP manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php

Retrieve distinct values from table

I have to print customer name once and all the products for each customer.My code is below.
<div id="Allproducts">
<?php
$AllprodsRes = $conn -> query("select * from sepproducts");
if($AllprodsRes ->num_rows > 0){
$result = $AllprodsRes -> fetch_array();
?>
<label for="name"><?php echo $result['name'] . " " . $result['surname']; ?></label>
<?php } ?>
<?php do{ ?>
<p><?php echo $result['product_name'] . " " //$result['count']; ?></p>
<?php }while($result = $AllprodsRes -> fetch_array()); ?>
</div>
view sepproducts
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `sepproducts` AS
select
`customers`.`name` AS `name`,
`customers`.`surname` AS `surname`,
`custproducts`.`product_name` AS `product_name`,
count(0) AS `count`
from
(`custproducts`
join `customers` ON ((`custproducts`.`custid` = `customers`.`custid`)))
group by `custproducts`.`product_name`
Any help is welcome and appreciated.
Thanks in advance.
What you can use is something like the following (assuming you use MySQLi):
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
$currentCustomer = null;
while ($result = $query->fetch_array()) {
$name = $result['name'] . ' ' . $result['surname'];
// Check to see if we're working with a new customer.
if ($currentCustomer != $name) {
echo $name . '<br />';
$currentCustomer = $name;
}
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
}
?>
Or if you only have one customer to worry about, use the following:
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
if ($query->num_rows > 0) {
$result = $query->fetch_array();
echo $result['name'] . ' ' . $result['surname'] . '<br />';
do {
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
} while ($result = $query->fetch_array());
}
?>
In effect, it checks if records have been found and if so, writes one result to our array $result. We then output the customer's name OUTSIDE of the loop (so this only occurs once), then use a do...while() loop to continue through the rest of the result array.
I hope this helps!
Depending on the databse you use you could join multiple rows into a single column. Ultimately this is a display problem. I say keep doing what you are doing and in your view keep track of the current name in the loop and compare to the next name - if the name is the same ignore it, when the name differs set current_name to this new name and continue. This way each name only shows once.

Mysql Field Data not displaying when a link is clicked?

I'm trying to get data from a database if a link is clicked.
I used the example codes suggested from this example -Getting mysql field data when a link is clicked?
But it doesn't work when I click on a link nothing comes up.
main.php
<?php
include('conn.php');
$sql2 = "SELECT Title FROM addpromo";
$result2 = mysql_query($sql2);
echo "<div id=\"links\">\n";
echo "<ul>\n";
while ($row2 = mysql_fetch_assoc($result2)) {
echo "<li> <a href=\"fullproject.php?title=\""
. urlencode($row2['Title']) . "\">"
. htmlentities($row2['Title']) . "</a>\n</li>";
}
echo "</ul>";
echo "</div>";
?>
This is displaying correct.but when I click at a link nothing is showing up in fullproject.php, Just a blank page.
fullproject.php
<?php
// Connect to server.
include('conn.php');
$projectname = isset($_GET['Title']);
$sql1 = "SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title'] . "<br />";
echo "<br /> ";
}
?>
Can someone help me to fix this, or any other way to make this(to get data from a database if a link is clicked) possible?
Change to this
main.php
<?php
include('conn.php');
$sql2="SELECT Title FROM addpromo";
$result2=mysql_query($sql2);
echo '<div id="links">';
echo '<ul>';
while($row2 = mysql_fetch_assoc($result2)){
echo '<li>'.htmlentities($row2['Title']).'</li>';
}
echo '</ul>';
echo '</div>';
?>
fullproject.php
<?php
if(isset($_GET['title'])){
include('conn.php');
$projectname= $_GET['title'];
$sql1="SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title']. "<br />";
echo "<br /> ";
}
}
?>
This is storing a boolean value $projectname= isset($_GET['Title']);, whether or not the title is set. Instead use $projectname = $_GET['Title'];
isset returns a boolean value (true/false) and you want the actual value of the variable:
$projectname= $_GET['title'];
Furthermore, you have to pass only the title as the URL parameter, without enclosing it within quotes. So there is an error in this line:
echo "<li> <a href=\"fullproject.php?title=" . urlencode($row2['Title']) . "\">"
Note the lack of \" after title=

Repeating a query

I want to search a table by inputing a random number for the ID, and for it to be successful, it has to match the specified tag. So far I have:
$query = "SELECT * FROM web_db WHERE P_Id = " . $random;
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_array($result)){
$name = $row[$id];
echo 'ID:' . $name . '<br>';
$name = $row[$url];
echo 'URL: ' . $name . '<br>';
$name = $row[$tag];
echo 'Tag:' . $name . '<p>';
}
}
This brings up one entry, any tag. How can I have it repeat until Tag matches a specified value?
You don't. SELECT statement returns everything that matches the followed conditions. So, if you want to query for a specific tag entry disregarding the P_Id, do this :
$query = "SELECT * FROM web_db WHERE tag = '".$tag."' ORDER BY RAND() LIMIT 1";
RAND() in this case will order the list randomly, while the query returns the first result that matches the tag used.
$result = mysql_query($query);
if(count($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo 'ID:' . $row['id'] . '<br>';
echo 'URL: ' . $row['url'] . '<br>';
echo 'Tag:' . $row['tag'] . '<p>';
}
} else {
echo 'no entries found';
}
if("sometag" === $name) break;
that exits the while loop. after you exit, you should check again to see if the tag was found or not

How to set permalink of your blog post according to date and title of post?

I am having this website http://www.finalyearondesk.com . My blogs post link are set like this.. http://www.finalyearondesk.com/index.php?id=28 . I want it to set like this ... finalyearondesk.com/2011/09/22/how-to-recover-ubuntu-after-it-is-crashed/ .
I am using the following function to get these posts...
function get_content($id = '') {
if($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * from cms_content WHERE id = '$id'";
$return = '<p>Go back to Home page</p>';
echo $return;
else:
$sql = "select * from cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1>' . $row['title'] . '</h1>';
echo '<p>' . "By: " . '<font color="orange">' . $row['author'] . '</font>' . ", Posted on: " . $row['date'] . '<p>';
echo '<p>' . $row['body'] . '</p><br />';
}
else:
echo '<p>We are really very sorry, this page does not exist!</p>';
endif;
}
And I am using this code to dispaly it on my index.php page...
<?php
if (isset($_GET['id'])) :
$obj -> get_content($_GET['id']);
else :
$obj -> get_content_summary();
endif;
?>
Any suggestions how to do this? And can we do this by using .htaccess?
The unfortunate thing about using mod_rewrite is that the data you are supplying in the form of a url is not the best way to query a database. But none the less you have year, month, day and title variables so you will need to rewrite your get_content function to query soomething like (depending on how you date is stored in the database.):
select * from cms_content
WHERE date='mktime(0,0,0,$month,$day,$year)'
AND title='$title'
ORDER BY id DESC
.htaccess would be something like:
RewriteRule ^(.*)/(.*)/(.*)/(.*)$ index.php?year=$1&month=$2&day=$3&title=$4

Categories