Basic PHP SQL Query not working - php

We have a basic PHP script to extract the title and description for each job from a MySQL database as simply display this information. This is what it looks like:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
$results = mysql_fetch_assoc($query);
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
Now, this only extracts one row from the database, but it should extract two. So, I tried the following to replace the while statement:
<?php foreach($results as $result) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
This statement doesn't work either. This just displays (weirdly) the first character of each column in the first row in the table.
Does anyone have any idea as to why this isn't working as it should?

In your while use same variable $result as you started:
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
and remove the first $results = mysql_fetch_assoc($query);

Result variable you have used is result not results
Replace
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
**$results = mysql_fetch_assoc($query);** // remove this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
to
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>

You already fetched the first row before your loop started, which is why it only prints the second row. Simply comment out that line:
#$results = mysql_fetch_assoc($query); # here is your first row,
# simply comment this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
You are also looping over $result but using $results in your while loop body.

Check this:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
?>

Change this line
<?php while($result = mysql_fetch_assoc($query)) {
to
<?php while($results = mysql_fetch_assoc($query)) {

Related

Concat () function or alternative solution in mysql query

I am trying to add a character before/after value in mysql query. but I can't make it work.
This is the part that doesn't work in my case:
$query = "select CONCAT ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
You can see the full code below. Any ideas why it doesn't work or can I get an alternative solution, please. thanks.
<div class="container">
<div class="left">
<?php
include ("etc/config.php");
$query = "select concat ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" size="44" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
?>
</div>
<div>
<?php
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
echo '</table>';
mysqli_close($link);
?>
</div>
</div>
For the 2nd half of your code, you can do this:
note you won't need to concat anything in your initial query
if(isset($_GET['mySelect'])) {
// configure every option here, if there's not pre/postfix, use a blank string
$prepostfixes = [
'DuRpt' => ['.', '.'],
'DaRpt' => ['', ''],
];
$myselect = $_GET['mySelect'];
if (!isset($prepostfixes[$myselect])) {
die ('Unknown Select'); // this will prevent sql injection
}
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
$prefix = $prepostfixes[$myselect][0];
$postfix = $prepostfixes[$myselect][1];
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $prefix . $row["mySelect"] . $postfix . "</td></tr>";
}
}
}
Just update your code and remove the duplicate of DuRpt from it.
$query = "select concat ('.', DuRpt) as DuRpt from DDtb order by DATE DESC";

php pagination with search not working together?

This is the small minor project from college. It ranks the students as per the no of votes. It does rank the student in the pagination but when the student profile is clicked the rank is not shown.
Ok so the below code works but the last part of the code does not display the rank in the output. how can I $num in both codes?
HOME
<br><br>
<form>
<input type="text" name="id" autocomplete="off" placeholder="enter student id">
</form>
<br><br>
<?php include 'conn.php'; ?>
<?php
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$result_per_page = 5;
$no_of_result = mysqli_num_rows($result);
$no_of_page = ceil($no_of_result/$result_per_page);
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
$page_first = ($page-1)*$result_per_page;
$sql = 'SELECT * FROM table ORDER BY votes DESC LIMIT ' . $page_first . ',' . $result_per_page;
$result = mysqli_query($conn, $sql);
$num = $page * $result_per_page -4;
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="x">';
echo '#';
echo $num++;
echo ' ';
echo '<a href="?id='.$row['id'].'">';
echo $row['name'];
echo '</a>';
echo '</div>';
}
echo '<br>';
for($page=1;$page<=$no_of_page;$page++){
echo ''.$page.'';
echo ' ';
}
echo '<br>';
?>
<?php
$name = $_GET['id'];
$sql = "SELECT * FROM table WHERE id=$name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<br>';
echo 'RANK = ';
echo '?';//display rank here?
echo '<br>';
echo 'NAME = ';
echo $row['name'];
echo '<br>';
echo 'VOTES = ';
echo $row['votes'];
echo '<br>';
}
} else {
//echo "0 results";
}
?>
The output of the above code.. I want to output the rank in the place of question mark.
current output
i want something like this
desired output

MySQL select where $id

I have a website with this code snippet:
<?php
mysql_connect('localhost','root','password');
mysql_select_db('news');
$id_article = $_GET['newsid'];
$query = mysql_query('SELECT * FROM news WHERE id="$id_article"');
{
echo '<div class="item"><h1>'.$query['subject'].'</h1><br />';
echo $query['full_content'].'<br / >';
echo date('D-M-Y', $query['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
}
?>
The $id_article gets the id from an previous request. The $id_article works, but the $query doesn't. $query['***'] still blank space. I don't know why. Please help me! Thanks a lot!
You don't get your query result. Use like below:
<?php
mysql_connect('localhost','root','password');
mysql_select_db('news');
$id_article = intval($_GET['newsid']);
$query = mysql_query('SELECT * FROM news WHERE id=' . $id_article);
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_assoc($query);
echo '<div class="item"><h1>'.$row['subject'].'</h1><br />';
echo $row['full_content'].'<br / >';
echo date('D-M-Y', $row['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
}
?>
Tip: use PDO or mysqli instead of mysql_ functions! Mysql_ functions are deprecated / not supported in new php versions!
Further, sanatize your input before passing to your query!
Use like this
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['id']. " - ". $row['date'];
You have not used mysql_fetch_assoc. Use as below :
$query = mysql_query('SELECT * FROM news WHERE id=' . $id_article);
$row = mysql_fetch_assoc($query);
if(count($row)>0)
{
echo '<div class="item"><h1>'.$row['subject'].'</h1><br />';
echo $row['full_content'].'<br / >';
echo date('D-M-Y', $row['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
}
change your this code
$query = mysql_query('SELECT * FROM news WHERE id="$id_article"');
{
echo '<div class="item"><h1>'.$query['subject'].'</h1><br />';
echo $query['full_content'].'<br / >';
echo date('D-M-Y', $query['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
}
to
$sql = "SELECT * FROM news WHERE id = $id_article";
$query = mysql_query($sql);
while($result = mysql_fetch_assoc($query));
{
echo '<div class="item"><h1>'.$result['subject'].'</h1><br />';
echo $result['full_content'].'<br / >';
echo date('D-M-Y', $result['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
}
There are a lot of errors in your code
mysql_query has been depreciated
Use the following code
and ckeck for the errors
<?php
mysql_connect('localhost', 'root', 'password');
$conn = mysql_select_db('news');
$id_article = $_GET['newsid'];
if($query = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM news WHERE id=$id_article"))){
echo '<div class="item"><h1>' . $query['subject'] . '</h1><br />';
echo $query['full_content'] . '<br / >';
echo date('D-M-Y', $query['date']) . '<br / >';
echo 'Posted by ' . $id_article;
echo '</div>';
}
?>
Try This..
$id_article = $_GET['newsid'];
$query = "SELECT * FROM news WHERE id='$id_article'";
$query1=mysql_query($query);
You should call a function to get the row returned by the query. You are trying to access the $query instead of the row. Your code should look like this:
<?php
mysql_connect('localhost','root','password');
mysql_select_db('news');
$id_article = $_GET['newsid'];
$query = mysql_query('SELECT * FROM news WHERE id="$id_article"');
if ($query) {
$row = mysql_fetch_assoc($query));
echo '<div class="item"><h1>'. $row['subject'].'</h1><br />';
echo $row['full_content'].'<br / >';
echo date('D-M-Y', $row['date']).'<br / >';
echo 'Posted by '.$id_article;
echo '</div>';
} else {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
?>
You can also take a look at the mysql_result(), mysql_fetch_array(), mysql_fetch_row() functions.

While nested lops in php fetching data from sql database

$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>".while($row = $result1->fetch_assoc())
{echo'<img src='".$row["image"]."'>;}
.</aside>}";
I have been using while loops for fetching data from table. My connection is working is perfect but I need another loop in the first that is not working. Isn't it the good way?
Update: I tried to finish echo and again started as follow but still an error
while($row = $result->fetch_assoc()) {
echo "<div id='post'><h1>"
.$row["heading"].
"</h1><div class='post-side'><img class='post-image' src='"
.$row["image"].
"'><div class='post-data'><p><strong>Age: </strong><span>$age</span></p><p><strong>Date of birth: </strong><span>"
.$row["day"].
"-"
.$row["month"].
"-"
.$row["year"].
"</span></p></div></div></div><div class='description'><p>"
.$row["description"].
"</p></div><div class='bottom-related'><aside class='related-post'>";
while($row = $result1->fetch_assoc())
{echo"<img src='"
.$row["image"].
"'>/";}.echo"</aside><aside class='ad2'>".$includead."</aside></div>";
}
echo "</div>";
} else {
echo "No table found";
}
$conn->close();
You're trying to concatenate to a string a WHILE loop; this is wrong.
You should echo your first part, end with it and then do your while loop, and echo the end afterwards:
Your quotes are a bit messed up as well
if ($result->num_rows > 0)
{
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>";
while($row = $result1->fetch_assoc())
{
echo'<img src="'.$row["image"].'">';
}
echo '</aside>';
}
You can't concatene while with String, it's a syntaxic error
Also, you have a probleme when trying to echo a String, you can use this syntax:
echo "PHP"; // will evaluate PHP variables and whitespace inside a string
echo 'PHP'; // will evaluate nothing;
But you can not start flushing a string ' and finish by " or vice-versa.
Here the correct code :
<?php
$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>" . $row["heading"] . "</h1><aside class='related-post'>";
while($row = $result1->fetch_assoc()) {
echo'<img src="' . $row["image"] .'">';
}
echo "</aside>";
}

unable to produce result correctly in div php

I'm not very sure how can I put them into words. I'm trying to display result in each div as shown in the image but unfortunately I'm only able to make it appear only in the "request for quote" div.
May I know where have I gone wrong?
<?php
$query2 = "SELECT * FROM client c, sales_card s WHERE c.id = s.client_id and emp_id_followup = '".$_SESSION["ID"]."'";
$result2 = mysql_query($query2);
if (mysql_num_rows($result2) > 0) {
while($row2 = mysql_fetch_assoc($result2)) {
$swimlaneID = $row2['swimlane_id'];
}
}
$query = "SELECT * FROM swimlane";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
echo '<div id="right">';
echo '<div style="border-style:solid; height:1020px;">';
echo '<h2>'. $row["swimlane_name"].'</h2>';
echo '<ul id="'. $row["shortform"].'">';
if ($swimlaneID == $row["id"])
{
echo $display-> $row["shortform"]();
}
echo '</ul>';
echo '</div>';
echo '</div>';
}
}else{
echo "no row";
}
?>

Categories