PHP Mysqli code not displaying query results - php

I want to output data from a query result. the query uses a print_r(json_encode($regions)) in another php page but it is not outputting anything. I have no errors in php, am I doing something wrong in mysqli code that it is not echoing anything?
//connecting to database
<?php
require_once('DbConnection.php');
//querying the database
$region_id = isset( $_GET['region_id'] )? $_GET['region_id']: false;
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name, sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales INNER JOIN region ON sales.region_id=region.region_id where region_id = $region_id") or die(mysqli_error($connection));
$result = mysqli_query($connection,"SELECT sales.region_id, sales.image_name, sales.price, sales.location, sales.Terms, sales.Contacts FROM sales INNER JOIN region ON sales.region_id=region.region_id where region_id = $region_id");
while ($row = mysql_fetch_assoc($sql)) {
?>
<div class="col-md-4">
<div class="thumbnail">
<a href="<?php echo "http://" . $_SERVER['SERVER_NAME'] ?>/photo/imageuploads/<?php echo $row["image_name"]; ?>">
<img src="<?php echo "http://" . $_SERVER['SERVER_NAME'] ?>/photo/imageuploads/<?php echo $row["image_name"]; ?>" alt="Lights" style="width:100%">
<div class="caption">
Image Name:<?php echo $row["image_name"]; ?>
Price:<?php echo $row["price"]; ?>
Location`enter code here`:<?php echo $row["location"]; ?>
Terms:<?php echo $row["Terms"]; ?>
Contacts:<?php echo $row["Contacts"]; ?>
</div>
</a>
</div>
</div>
<?php
}
?>

In your SQL, your where clause refers to region_id, which in this case is defined in two tables (sales and region), if you need both of these tables, then you need to qualify which table you want to use the region_id from
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name,
sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales
INNER JOIN region ON sales.region_id=region.region_id
where region.region_id = $region_id") or die(mysqli_error($connection));
but as you don't use any columns from region in your result, you could just drop the join...
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name,
sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales
where region_id = $region_id") or die(mysqli_error($connection));
Also as Barmar says, remove the second execution of the query otherwise this may fail and stop the script as well.
Also where you check if $_GET['region_id'], this should be more a case of if it isn't set, then don't do anything. Just setting it to false will cause more problems.

Related

I am using two tables from database and to display on a page using PHP

I am trying to make a page which has to get data from two tables. and display on a page. this displayed data is an array. for example if the displayed data is say USA which come from Table A,and if you click on USA...then it should go to Table B and get all the states from Table B related to USA and display it on the page. so how to join the tables?
the code used is as below:
<?php
require("libs/config.php");
$pageDetails = getPageDetailsByName($currentPage);
$stateDetails = getStateDetailsById($page_id);
include("header.php");
?>
<div class="row main-row">
<div class="col-md-8">
<section class="left-content">
<h2><?php echo stripslashes($pageDetails["page_title"]); ?></h2>
<?php echo stripslashes($pageDetails["page_desc"]); ?>
<!--New-->
<?php
$page_id = $pageDetails["page_id"];
if ($_GET["id"] <> "")
{
// if we are on page.php page. get the parent id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE status = 'A' AND parent = :parent ORDER BY sort_order ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($pageDetails["parent"]));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
?>
<div class="col-sm-12">
<?php
if (count($pageResults) > 0)
{
?>
<section>
<h2>States</h2>
<div>
<div class="row">
<?php foreach ($pageResults as $rs)
{ ?>
<div class="col-sm-3">
<ul class="state">
<li class="state">
<div class="state-dist"><h3><?php echo stripslashes($rs["page_title"]);?></h3>
<div class="state_img"><img src="images/<?php echo stripslashes($rs["page_image"]);?>"height="50" width="180"</div>
<br />
<br />
<div class="page-actions">
More Details
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
</div>
</section>
<?php } ?>
</section>
</div>
So,
when i click on the link created by the last part of the code then it should go to TABLE.STATES fetch the records and display it. Currently this code goes to the same table TABLE_PAGES.
I know i have to use table joins but I am not able to code it.
Currently this code goes to the same table TABLE_PAGES.
As far as I think, you should change TABLE_PAGES to TABLE_STATES in the following part of your code:
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_STATES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
I'm assuming you'll be running the following SQL code:
SELECT * FROM TABLE_STATES WHERE TABLE_STATES.page_id = TABLE_PAGES.page_id
which you can execute to get a list of all the states belonging to the parent (TABLE_PAGES) table.
TIP: Always try to use table names that represent real-world entities AND serve the purpose of the actual data that you want to store. In your case TABLE_COUNTRIES would be a more conventional name for a table that represents the entity country.
You could also run a left join as such:
SELECT TABLE_STATES.* LEFT JOIN TABLE_COUNTRIES ON TABLE_COUNTRIES.page_id = TABLE_STATES.page_id AND TABLE_COUNTRIES.page_id = <your provided value>

get url id in php and display result in html

Hi i have written this code in order to get the news id from url and display the news result from this id which is stored in mysql. I dont know what i am doing wrong. But i am getting any output. I have also test my query which is running fine in mysql.I am doing small misatke which is not able to identif may be syntax or quotation somewhere. Thanks.
Here is my Url:
http://autodo/admin/news.php?id=2043
Here is my code:
<?php
$ID=$_GET['id'];
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id =".$ID."
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
echo $sql_select=mysql_query($sql);
if($row = mysql_fetch_assoc($sql_select)){
$news_id= $row['id'];
$news_datum= $row['datum'];
$news_text= $row['text'];
$news_headline= $row['headline'];
?>
<div class="welcome-rahmen lng toggleNews" id="<?= $news_id ?> ">
<p class="welcome-breadcrump"><?= $news_datum ?></p>
<p class="welcome-subheadline"><?= $news_headline ?></p>
<div class="newsText">
<?= $news_text ?>
</div>
</div>
<? } ?>
You should concatenate $ID and sql string by .
For example:
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id =".$ID."
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
You have used <?= echo - <?= alone is the same as <?php echo Additionally, as another pointed out you are missing several ; at the end of lines.
Regardless, I would encourage you to use prepared statements or otherwise sanitize the data you are pulling from the query string as your query as written is vulnerable to SQL injection.
first change quote to variable in where of query like
WHERE ad_news_texte.id ='$ID'
then no use of echo in
<?= echo $news_datum ?> try in all of your code <?= $news_datum ?>
so your whole code will be
<?php
$ID=$_GET['id'];
$sql="SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id FROM autodo.ad_news_texte, autodo.ad_news WHERE ad_news_texte.id ='$ID' GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
$sql_select=mysql_query($sql);
$checkrow = mysql_num_rows($sql_select);
if($checkrow > 0) {
if($row = mysql_fetch_assoc($sql_select)){
$news_id= $row['id'];
$news_datum= $row['datum'];
$news_text= $row['text'];
$news_headline= $row['headline'];
?>
<div class="welcome-rahmen lng toggleNews" id="<?= $news_id ?> ">
<p class="welcome-breadcrump"><?= $news_datum ?></p>
<p class="welcome-subheadline"><?= $news_headline ?></p>
<div class="newsText">
<?= $news_text ?><?php }
}
else {
echo 'query does not return any rows';
}?>
Some mistakes,
You mixing shorthand and echo for printing output.
Missing ; semi-colon at end of echo statment.
Syntax error in query
Firstly turn on your errors adding ini_set("display_errors",1); on top of your file.
Use below statemnt for everywhere you output the variable,
<?php echo $news_id; ?>
Or,
<?= $news_id ?>
Query should be,
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id = '$ID'
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

query working with like statement but not with fulltext mysql index

am trying to create a search engine to enable users data search. I tried using like in the sql query and it works. Now i want to use mysql fulltext index as in the code below but its not displaying any data when search. my table is created as myislam with fulltext index enabled. below is the code
<?php
include('searchajax_db.php');
if($_POST) {
$q=mysql_real_escape_string($_POST['search']);
$sql_res=mysql_query("select * from articles WHERE MATCH(title,body) AGAINST ('$q')
order BY MATCH(title,body) AGAINST ('$q')");
//$sql_res=mysql_query("select id,title,body from articles where title like '%$q%' or body like '%$q%' ");
//
if($sql_res === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($sql_res)) {
$ut=$row['title'];
$ub=$row['body'];
$b_ust=''.$q.'';
$b_emb=''.$q.'';
$final_u = str_ireplace($q, $b_ust, $ut);
$final_e = str_ireplace($q, $b_emb, $ub);
?>
<div class="show" align="left">
<?php echo '<a data-role="button" data-transition="fade" data-icon="arrow-r" data-iconpos="right" data-inline="true" href=profile.php?id='.htmlentities($row["id"], ENT_QUOTES, "UTF-8") .' title="Click to Find ">'.'<font color=orange></font>'.''
?>
<?php echo '<font color=greenyellow>' ?>
<span class="name"><?php echo htmlentities($final_u, ENT_QUOTES, "UTF-8"); ?></span> <br/>
<?php echo htmlentities($final_e, ENT_QUOTES, "UTF-8"); ?><br/>
<?php echo '</font>' ?>
</div>
<?php }} ?>
You don't need to use MATCH everywhere. The WHERE condition is where you determine which rows are retrieved from the table. Right after SELECT is where you choose which columns from those rows are displayed. ORDER BY determines which column and direction the rows are sorted by.
This example would probably be sufficient:
SELECT title, body FROM articles WHERE MATCH(title,body) AGAINST ('$q') ORDER BY title ASC
I also will note that you should use prepared statements with PDO or MySQLi as it is better protection than using mysql_real_escape_string.

I need to pull from two tables into a loop and match the data

Please forgive me if I'm going about this the wrong way I don't have much experience in PHP development.
I need to list some real estate listings on a page, which is easy enough, but where I'm having trouble is trying to match them with the proper image. The images are stored on my server and I have the file path saved in one table and all the property info stored in another table.
This is what I have right now and it kind of works.. except for it is showing each listing twice. Once with pic once with out.. I know there has to be a much better way then this..
<?php
$sql="SELECT * FROM $tbl_name, documents_main WHERE show_listing='1' and user_type='1'";
$result=mysql_query($sql);
// Start looping rows in mysql database.
while($rows=mysql_fetch_array($result)){
$payment = $rows['price'] * .09 / 12;
$path = $rows['path'];
$id = $rows['id'];
$note_id = $rows['note_id'];
?>
<div class="row clearfix">
<div style="width: 120px; float: left;">
<?php
if($note_id == $id){
echo "<img src='$path'>";
} else {
echo "";
}
?>
</div>
<div style="float: left;">
<? echo $rows['prop_city']; ?>, $<? echo $rows['price']; ?>$<? echo round($payment); ?>
</div>
</div>
<?
// close while loop
}
?>
I can post the tables if that is helpful.
If you are using two tables in your query, there should be a column in the second table linking the row to a row in the first column
Once you identified this field, write your query like this :
$sql="SELECT * FROM $tbl_name, documents_main WHERE show_listing='1' and user_type='1' and $tbl_name.FIELD_TO_BE_DEFINED = documents_main.ANOTHER_FIELD_TO_BE_DEFINED";
Or :
$sql="SELECT * FROM $tbl_name inner join documents_main on $tbl_name.FIELD_TO_BE_DEFINED = documents_main.ANOTHER_FIELD_TO_BE_DEFINED WHERE show_listing='1' and user_type='1'";

Why do I have to call query twice?

why do I need to query twice here? Why can't I just query the one below, change it to 'SELECT * FROM ...' and use it query for the rest of the script? When I try to do that, the second half part of my script won't recognize the query from the beginning, and I have to query again.
$getImages = 'SELECT image_id, image_name FROM images';
<select name="image_id">
<?php while ($row = $images->fetch_assoc()) { ?>
<option value="<?= $row['image_id']; ?>"
<?php if (isset($_GET['image_id']) && $_GET['image_id'] == $row['image_id']) {
echo 'selected';
} ?>
><?= $row['image_name']; ?></option>
<?php } ?>
</select>
$sql = "SELECT image_name, caption FROM images WHERE image_id = $image_id";
$result = $conn->query($sql);
if ($result->num_rows) {
$row = $result->fetch_assoc();
?>
<figure><img src="images/<?= $row['image_name']; ?>.jpg" width=600px height=auto>
<figcaption><?= $row['caption']; ?></figcaption>
</figure>
<?php } else { ?>
<p>Image not found</p>
<?php } ?>
thank you :)
The first loop exhausts all the results of the query. You need to either re-execute the query or rewind the result resource back to the first record.
Far far far easier to pull your object to an array, then iterate through the array so that you aren't getting stuck with exhausting our object rows.

Categories