I have one table which contains events and dates, and another which contains the guestlist for each of these nights. I can print the nights like so:
$day = date("l");
$date = getFullDateString($day);
$result = mysql_query("SELECT * FROM nights WHERE day = '$day' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>";
echo $row[name];
echo " (";
echo getFullDateString($row[day]);
echo ")</h2>";
}
The problem is that for each of these events I want the guestlist to be printed below it. I've tried putting another while loop inside, but even the test echo doesn't work.
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = 'getFullDateString($row[day])'") or die(mysql_error ());
while($row2 = mysql_fetch_array($result2)) {
echo $row2[0];
echo "test";
echo "<br />";
}
Essentially I want the following:
Event 1
Name 1
Name 2
Name 3
Event 2
Name 1
Name 2
Name 3
You have a method inside the query string which won't be run.
Try:
$sql = "SELECT DISTINCT guest FROM guestlists WHERE night = '".$row['name']."' AND `date` = '".getFullDateString($row['day'])."'"
Also, date is a reserved word in MySQL and should be encapsulated within backticks or changed to something else.
Additionally, the mysql_ functions are being deprecated and it is recommended to replace them with PDO or MySQLi.
Take a look at Complex (curly) syntax for string parsing to learn the proper way to embed your variables in the string.
Try this...
$result = mysql_query("SELECT * FROM nights WHERE day = '".$day."' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>".$row[cname]."</h2>";
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = '".getFullDateString($row[day])."'") or die(mysql_error);
while ($row2 = mysql_fetch_array($result2))
{
echo $row2[cname];
}
}
Related
I have a SQL database of university students, with the following details:
Table_name: register
Column_names: position, tertinst
The data in the database will look something like this:
Coach..........UCT
Athlete........Tukkies
Official.......University of JHB
Athlete........Tukkies
Athlete........Tshwane Tech
Manager........UCT
I need to count the amount of students who are athletes(position), per university(tertinst) and the output has to be something like this:
UCT.....................735
University of Jhb.......668
Tukkies.................886
this is my attempt:
$positionx = 'Athletes';
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(position) FROM register WHERE position = '$positionx' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['COUNT(tertinst)'] . '......' . $row['COUNT(position)'];
}
$conn->close();
I get no result when the code is executed and I have searched for a different solution for hours, without success.
I made a few mistakes, and corrected the syntax in the sql count, as well as the echo. Here is the solution to my problem:
<?php
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(*) total FROM register WHERE position = 'Athletes' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$tertinst = $row["tertinst"];
echo $tertinst . '......' . $row['total'] . '<br>';
}
$conn->close();
I want to echo each car ID which is available in a period between the start_date and the end_date. So far i got this with some help here on SO. This gives me a page not responding, if I delete the second part (commented in the script down here) it is eching all the car id's but not only the ones which are available ofcourse. What is wrong with the script? Because i cant figure out what i did wrong here.
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$items = array();
$result = mysqli_query($con, "SELECT * FROM invoice_line ");
while ($car = mysqli_fetch_array($result)) {
echo $car['car_car_id'];
//second part
$car_available = mysqli_query($con, "SELECT *
FROM invoice_line
WHERE car_car_id = $car['car_car_id']
and start_date>='$start_date'
and end_date<='$end_date'");
echo $car_available['car_car_id'];
} // end second part
?>
The process you are doing is:
1. fetch all lines from invoice_line
2. for each line, fetch all lines between two dates.
You do it wrong, because you do not have to use two queries. You can use one:
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$result = mysqli_query($con, "SELECT car_car_id FROM invoice_line where start_date>='$start_date' AND end_date<='$end_date'");
while ($car = mysqli_fetch_array($result)) {
echo $car['car_car_id'];
} // end second part
?>
I would add distinct for car_car_id, in order to get only one line per car id. if you want other data frome this line, you have to add it in the "SELECT" query
Will you try this code? Hope it may solve your problem you're echoing $car['car_car_id'] twice in your code but you missed the loop of your available cars
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$items = array();
$result = mysqli_query($con, "SELECT * FROM invoice_line ");
$carid = null;
while ($car = mysqli_fetch_array($result)) {
$carid = $car['car_car_id'];
echo $carid;
//second part
$car = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = '$carid' AND start_date>='$start_date' AND end_date<='$end_date'");
while ($car_available = mysqli_fetch_array($car)) {
echo $car_available['car_car_id'];
}
} // end second part
?>
i know it might be somthing old but i need to declare a variable or that is what i think.
basically i got a table name request and i need to fetch the last value from the column date. which i did in phpMyAdmin. now i need to fecth that exact value and use it as a variable in php.
<?php
include 'mydb.php';
require_once 'init.php';
$user_id = $user->data()->id ;
$data = mysql_query("SELECT date FROM request WHERE user_id= $user_id ORDER BY latest_request DESC LIMIT 1") or die(mysql_error());
$test = array();
while($row = mysql_fetch_array( $data ))
{
echo "<td>" .$row['date']. "</td>" ;
}
?>
<?php
$current_date = echo "<td> .$row['date']. "</td>" ;
// result im expecing is 2016-10-17 23:53:48
// echo " $current_date" --- will be 2016-10-17 23:53:48
>?
but all i get is an empty value, how can i accomplish this
If you want to have only one, last row, then maybe better idea would be something like that:
$sql = 'SELECT date FROM request WHERE user_id= $user_id ORDER BY latest_request DESC LIMIT 1';
$result = mysql_query($sql, $yourDBCon) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
This solutions brings you only one row.
Also make sure you get anything from sql statment.
Here's a working code (based on the fact that you say that the while()-loop works, and that you actually get a result with the $row['date']:
<?php
include 'mydb.php';
require_once 'init.php';
$user_id = $user->data()->id ;
$data = mysql_query("SELECT date FROM request WHERE user_id = $user_id ORDER BY latest_request DESC LIMIT 1") or die(mysql_error());
while($row = mysql_fetch_array( $data )) {
echo $lastdate = '<td>'.$row['date'].'</td>' ;
}
echo $current_date = '<td>'.$lastdate.'</td>' ;
?>
i was able to solve this issues by using pdo insted
<?php
$base_datos = DB::getInstance();
$base_datos->query ("SELECT req_date FROM request wHERE user_id = $user_id order by req_date desc limit 1");
$last_date = $base_datos->results();
$request_last_date = $last_date[0];
$c_date =$request_last_date->req_date;
echo "$c_date";
?>
this was to get a value from a table on my database and declared it as a value
I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop
This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.