I'm using this w3schools way to get data from the database:
$sql = "SELECT num_of_reservations FROM table WHERE date = '$date";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["num_of_reservations"];
}
I have database which looks like this:
id - date - num_of_reservations - name
1 - 2017-02-02 - 3 - somebody
2 - 2017-02-02 - 5 - somebody
3 - 2017-02-02 - 7 - somebody
This works fine if I want to echo rows from the database, but now I need to make form which allows you to make reservation only if there is less than 15 reservations already at the same day. Problem in my current design is that every num_of_reservations row is going to different Array (because of while loop I quess) and I need to make them to + (3+5+7) so I can compare, is the num_of_reservations <=15 If it is I display ticket buying screen and if it's not I tell to pick another day.
You can use another query to get the sum of all reservations:
$sql = "SELECT SUM(num_of_reservations) AS sum_of_reservations FROM table WHERE date = '$date'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if ($row['sum_of_reservations'] <= 15) {
//display ticket buying screen.
} else {
//tell to pick another day.
}
Related
Maybe this question is so basic i cant find it explained.
I have a table with 2 values . instructions | valuations which echos from mysql.
I was looking to get the %(percent) value of instructions to valuations.
i.e. 10 appointments / 5 sales = 50% conversion rate.
the sum would be Sales / Appoints x 100 = %
Any idea how i would echo this into 'percentage' column on my html table?
$query = "SELECT * FROM office_figures2016";
$result = mysqli_query($conn, $query);
while($office_figures2016=mysqli_fetch_assoc($result)){
echo "<tr>";
//changes date to english format from a time stamp
echo"<td>".$office_figures2016['id_why']."</td>";
echo"<td>".date('d-m-Y',strtotime($office_figures2016['date_figures']))."</td>";
echo"<td>".$office_figures2016['valuations']."</td>";
echo"<td>".$office_figures2016['instructions']."</td>";
echo"<td>".$office_figures2016['percentage of above']."</td>";
$query= "SELECT *,
concat(round(( instructions/valuations * 100 ),2),'%') AS percentage
FROM office_figures2016";
$result = mysqli_query($conn, $query);
while($office_figures2016=mysqli_fetch_assoc($result)){
//echo "$applicant_card[id].$applicant_card[first_name]"; //this echos out a few columns = id and first_name
echo "<tr>";
//changes date to english format from a time stamp
echo"<td>".$office_figures2016['id_why']."</td>";
echo"<td>".date('d-m-Y',strtotime($office_figures2016['date_figures']))."</td>";
echo"<td>".$office_figures2016['valuations']."</td>";
echo"<td>".$office_figures2016['instructions']."</td>";
echo"<td>".$office_figures2016['percentage']."</td>";
echo"<td>".$office_figures2016['firsts']."</td>";
echo "<td><a href='edit_figures.php?edit=$office_figures2016[id_why]'>Edit</a></td>";
//echo "<td><a href='delete_applicant.php?id=$office_figures2016[id]'>x</a></td></tr>";
}
You shouldn't create such a column - it is bad habit to have duplicate values in database. It is simple value, so you can calculate it each time, for example:
SELECT a.a, a.b, (a/b) FROM a ORDER BY (a/b);
If you really want to add it, you can simply create column in phpMyAdmin and then update it width sql
UPDATE A SET a_b=a/b
I have been trying to manage duplicate data which is shown to users.
I thought I can add the varibales to arrays and use the function array_unique
I want to be able to manage the rows which contain a duplicate date and split them into different sections for example
if(duplicate.exists == true)
{
//do something to the duplicate row
}
else
{
//do something to the row which isnt a duplicate
}
I cant figure out why array_unique is not working.
Help would be appreciated, Thanks.
$result = mysqli_query($con, "SELECT *
FROM quotes order by DATE asc ");
$index1 = array();
$fact1 = array();
$newDate1 = array();
while ($row = mysqli_fetch_array($result)) {
$index = $row['id'];
$dbdate = $row['date'];
$fact = $row['quote'];
$newDate = date("d-m-Y", strtotime($dbdate));
$index1[] = $fact;
$fact1[] = $fact;
$newDate1[] = $newDate;
}
Then have a function which loops through each array and finds out if a certain date has already exists.
for($i=0; $i<count($index1); $i++) {
echo(array_unique($newDate1));
}
else
{
}
Thats an example of the data that will be in the DB.
It's the id, fact, date example 1, fact, 2015-01-22
1 Steve Jobs unveiled the first Apple #Mac computer and changed technology forever (1984) - 2015-01-24
2 In 2011, the Urban Technology Innovation Center was launched in New York City - 2015-01-25
3 #Bebo was launched a whole decade ago today (2005), who feels old? - 2015-01-26
4 Sun Microsystems was acquired by Oracle Corporation for $7.4 bn (2010) - 2015-01-27
Considering you are sorting your query on date and that makes something a duplicate, all you need to do is track the last date.
$lastdate = '';
while ($row = mysqli_fetch_array($result)) {
$dbdate = $row['date'];
if ($lastdate==$dbdate) {
//duplicate
} else {
//first or unique
}
$lastdate = $dbdate;
}
It can be quicker to do this in SQL
Find the duplicates
SELECT * FROM quotes GROUP BY `date` HAVING COUNT(`date`) > 1 order by DATE asc
Find the non-duplicates
SELECT * FROM quotes GROUP BY `date` HAVING COUNT(`date`) = 1 order by DATE asc
So as noted by the OP, he wants a way to detect duplicates and not remove them.
To detect duplicates you can use something like this, answered in another question.
I would prefer this:
function array_has_dupes($array) {
return count($array) !== count(array_unique($array));
}
Use SQL "count" and "group".
create table z (x varchar(100),y varchar(100));
insert into z values ('a','b');
insert into z values ('a','b');
insert into z values ('a','c');
select x,y,count(*) as count from z group by x,y;
You get values:
+------+------+-------+
| x | y | count |
+------+------+-------+
| a | b | 2 |
| a | c | 1 |
+------+------+-------+
And use it in php code.
I am displaying the complete record of the user in the My profile section, I am fetching all the rows , but the problem is within the rows I've got two fields as arrays, which are 'secondarySubject' and 'secondaryGrade' now I want the display to be something like this
2002-2004 ----------- A Level ------- School Name
Science A
Maths B
I am able to display them but it prints the dates, school name and level name with every subject rather than just once for all the subjects. I am posting my code, can someone pleaseeee help me with it.
$result2 = $db->query('
SELECT *
FROM secondaryEducation
WHERE userID = "'.$graduateID.'"
ORDER BY secondaryFinishDate DESC
');
$totalRows2 = mysql_num_rows($result2);
if($totalRows2 > 0)
{
$html .= '<h2>Secondary Education: '.$option.'</h2>';
while($row = mysql_fetch_assoc($result2))
{
$startYear = formatDate($row['secondaryStartDate'], 'Y');
$finishYear = formatDate($row['secondaryFinishDate'], 'Y');
if (!empty($row['secondaryGrade']))
$secondaryGrade = getSecondaryGradeName($row['secondaryGrade']);
else
$secondaryGrade = $row['secondaryGradeCustom'];
$html .= '
<div class="secondaryListing">
<div><strong>'.$startYear.' - '.$finishYear.' '.stripslashes($row['secondarySchool']).'</strong></div>
<div>'.stripslashes(getSecondaryLevelName($row['secondaryLevel'])).' in '.stripslashes(getSecondarySubjectName($row['secondarySubject'])).' - '.stripSlashes($secondaryGrade).'</div>
</div><!-- End education listing -->
';
}
}
It looks like those are inside the while statement. Every time it loops it will include it. Try moving it outside the while statement.
sorry about the title, i really did not know what I should call it, but hopefully you will be able to aid me with my script.
What I am trying to achieve (with my less than 5 hour total experience with any sort of "programming", hence the horrid coding) is to send one query X times, and then put a new query into those newly created rows.
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT max(ordrenr) FROM antalstabel") or die(mysql_error());
$maxordrenr = mysql_query($sql);
$nextnumber = $maxordrenr + 1;
$maxplusantal = $maxordrenr + $antal;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr) VALUES ('$nextnumber')") or die(mysql_error());
}
}
This is my first query, what this does (or what I want it to do) is to get the max ID of the table "antalstabel" add +1 and then count a certain amount up which is defined as $items untill it has executed X rows.
My first issue here, is the fact that my table consists of two key primaries, so returning a query like this would result in an error since after one return the two rows would be identical and will not execute.
The second issue is the fact that the next value in the table should not be inserted X times after each other, but rather be certain IDs added in afterwards.
What I am trying to achieve ultimately (not only by this script, but this is the current issue) is something like this:
ordrenr(key)varenr(key) antal
1 3 1
1 2 2
2 1 4
3 1 1
3 2 1
3 3 1
Does this make any sense whatsoever for anyone and can anyone tell me whether my method of doing this is jsut hopeless or have some better ideas for me to use as execution for ending up with something like this?
Should I not use primary keys or how does this work?
Thank you for even taking the time to read this :)
-Victor
EDIT for future:
changed script to this for it to work:
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT * FROM antalstabel ORDER BY ordrenr DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_assoc($sql);
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$maxplusantal = $maxordrenr + $antal;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','1236')") or die(mysql_error());
}
$maxordrenr = mysql_query($sql);
should be
$maxordrenr = mysql_result($sql,0);
I have created a lottery script in php. My problem is now selecting more then one winner. Because it is possible for players to have the same number on their tickets. Here I am supplying the two table structures and the source code.
lotto_game {
id(int)
jackpot(int)
status(varchar10)
pick_1(int)
pick_2(int)
pick_3(int)
pick_4(int)
pick_5(int)
tickets_sold(int)
winner(text)
}
lotto_picks {
lotto_id(int)
user_id(int)
choice_1(int)
choice_2(int)
choice_3(int)
choice_4(int)
choice_5(int)
ticket_status(int)
}
These are my two tables with in my database. For examples sake we will create 2 users with the id's 1, and 2. So what happens is when the script runs it is suppose to change the lotto_game status from 'active' to 'finished' then add the random lottery numbers into each pick_* column.
$one = rand(1,30);
$two = rand(1,30);
$three = rand(1,30);
$four = rand(1,30);
$five = rand(1,30);
mysql_query("UPDATE `lotto_game` SET
pick_1 = '$one',
pick_2 = '$two',
pick_3 = '$three',
pick_4 = '$four',
pick_5 = '$five',
status = 'finished'
WHERE status = 'active'");
That wasn't too hard I will admit. But this is just the beginning of the end.
$lotto['tickets'] = mysql_query("SELECT ticket_id FROM `lotto_picks` WHERE ticket_status='valid'");
#$lotto[winners] = mysql_query("SELECT ticket_id,user_id FROM `lotto_picks` WHERE choice_1 = '$one' AND choice_2 = '$two' AND choice_3 = '$three' AND choice_4 = '$four' AND choice_5 = '$five'");
$lotto['num_tickets'] = mysql_num_rows($lotto['tickets']);
#$lotto[winner_id] = mysql_fetch_array(#$lotto[winners]);
$lotto['jackpot'] = mysql_query("SELECT jackpot FROM `lotto_game` WHERE status='active'");
$lotto['winner_jackpot'] = mysql_fetch_array($lotto['jackpot']);
$lotto['num_winners'] = mysql_num_rows($lotto['winners']);
//echo #$lotto['num_tickets'];
//echo #$lotto['num_winners'];
$winner = $lotto['num_winners'];
//echo #$lotto['winner_id']['user_id'];
$jackpot = $lotto['winner_jackpot']['jackpot'];
$id = #$lotto[winner_id][user_id];
if ($winner == 1) {
mysql_query("UPDATE `character` SET
decivers = decivers +'$jackpot'
WHERE user_id='$id'");
}
This is what I have come up with and it really seems to work with one winner. But I just cant figure out where to go from here. I have tried using some arrays but nothing works. I know what needs to be done but can't figure out how to do it.
When I search for winners I need to put into an array all their user id's.
so extra decivers is money, if anyone is confused on that. The status on the tickets doesn't really matter here but if you must know it just determines if the ticket_status is 'valid' or 'invalid'
i think you've chosen the wrong storage formats for your picked numbers. The standard approach is to use binary values which have N-th bit set if the number N is choosen.
Consider this example: user chooses numbers "2 4 5 9 11". Setting corresponding bits to 1 gives '10100011010' which is decimal 1306. Now the lottery picks "4 7 9 12 13" which is '1100101001000' == 6472. Perform a bitwise AND on both values and count the number of bits set in the result:
SELECT BIT_COUNT(1306 & 6472)
this immediately tells us that the user has 2 correct picks. Just as easy you can select "full" winners:
SELECT * FROM tickets WHERE BIT_COUNT(tickets.pick & lotto.pick) = 5
or sort the tickets by the number of correct picks
SELECT * FROM tickets ORDER BY BIT_COUNT(tickets.pick & lotto.pick) DESC
$winners_array = array();
if(mysql_num_rows($lotto['winners'])!=0){
while($row =mysql_fetch_array($lotto['winners'])){
if(!in_array($row['user_id'],$winners)) $winners[] = $row['user_id'];
}
}
$winners will be an array with all the winners user_ids