get url id in php and display result in html - php

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.

Related

PHP Mysqli code not displaying query results

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.

Sorting query results with column head

I have a typical SQL query that returns results like this:
$result_acc_man = "SELECT * FROM mgap_management WHERE account_manager_id = '" . $_SESSION['account_manager_id'] . "' ORDER BY mgap_sales_pres";
$stmt = $pdo->prepare($result_acc_man);
$stmt->execute();
while($row_acc_man = $stmt->fetch(PDO::FETCH_ASSOC))
{
$salespres = $row_acc_man['mgap_sales_pres'];
$regvp = $row_acc_man['mgap_regional_vp'];
$areasales = $row_acc_man['mgap_area_sales_manager']
?>
<p class="asminfo"><span>Your ASM: <?php echo $areasales;?></span></p>
<p class="asminfo"><span >Your Regional VP: <?php echo $regvp; ?></span></p>
<p class="asminfo"><span >Your Sales President: <?php echo $salespres; ?></span></p>
<?php
}
?>
here are the column headers
<div id="viewheadaccept">
<span class="namecustaccept1">ACCOUNT NAME </span>
<span class="custaccept">ACCOUNT TYPE</span>
<span class="recoverycustaccept">OPPORTUNITY SIZE</span>
</div>
I need to add the ability to click on the column names and sort the data. Is there an easier way to accomplish this other than creating multiple linked pages with different queries that contain the sort?
Thanks!
You could provide a parameter to replace mgap_sales_pres. So send a orderBy parameter via the url stirng.
You would need to escape the variable for security. Normally this wouldn't be recommended, but since prepared statements can't inject variables into the ORDER BY clause, it's the only option for now.
For example mysql_real_escape_char($_GET['orderBy'])
Or if you are really paranoid you could use a switch case statement to check for a validate column name.

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.

How to use while loops in mysqli query

Am sorry for the really stupid question. i have a code like so and i would like the result to be done on a while loop. i was using mysql befor and the query was simple and executed well.
example
$sql_query = mysql_query($query);
while($row = mysql_fetch_array($sql_query)
{
$data_a = $row['a']; $data_b = $row['b'];
}
now i use oop and i have a database class and a connection handler that is injected in to the new class am extending from the database class. my proble no is after the code executes, i get this error method *mysqli_stmt::fetch_assoc()* here is my code
<?php
class recentWorks extends DatabaseModelBase
{
public function show($tbl, $num_to_show, $site_url="")
{
$statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT '.$num_to_show.' ');
$statement->execute();
while ($recent_results = $statement->fetch_assoc())
{
$featured_work_name=$recent_results['name']; $featured_work_url=$recent_results['url']; $featured_work_thumb=$recent_results['img_thumb'];
$featured_work_id=$recent_results['id'];$featured_work_desc=$recent_results['desc'];$featured_work_img=$recent_results['img_url'];
?>
<li>
<a href="<?php echo $featured_work_img; ?>" class="fancybox thumb poshytip" title="Click To View Enlarged Image">
<img src="<?php echo $featured_work_thumb; ?>" width="282px" height="150px" alt="<?php echo $featured_work_name; ?>' Image" />
</a>
<div class="excerpt">
<span class="main_header"><?php echo ucwords($featured_work_name); ?>
</span>
<?php echo substr($featured_work_desc,0,300); ?>
</div>
</li>
<?php
}
$statement->close();
}
}
?>
please someone debug this for me
Let's see what you had before
$sql_query = mysql_query($query);
`----- missing error checking and handling
while ($row = mysql_fetch_array($sql_query))
`---- missing error handline
{
$data_a = $row['a']; $data_b = $row['b'];
`----- complicated way of setting variables as arrays
}
Now let's see what you have now (selected lines)
$statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT '.$num_to_show.' ');
`---- using prepare as if it would have been mysql_query()
$statement->execute();
`----- same here
This is wrong. Just telling you. I suggest you search for some well-working mysqli_* tutorial first. One that either explains you how to build SQL queries and fire them and that explains what prepared statements are and how to use them.
My suggestion: Start with the PHP manual, it compares the different libraries and shows examples for all mysql, mysqli and PDO.
You have even a comparison side-by-side of mysql and mysqli for a more easy migration: Dual procedural and object-oriented interface.

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