Trouble sending various queries into proper rows for set times - php

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);

Related

PHP PDO pagination foreach

I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]
This is my code:
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
foreach ($nodes2 as $n1) {
echo "text";
}
I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.
Something that I tried
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10);
foreach ($chunked[$page_of_pagination] as $n1) {
echo "text";
}
If someone could help out, I appreciate it.
You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.
You need to do this:
$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";
What LIMIT does:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants
More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html
Then you can proceed getting the result and showing it.
Edit after comment:
To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:
SELECT COUNT(*) as count FROM comments WHERE shown = '1'
Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:
$totalNumberOfPages = ceil($count / $rowsPerPage);
and to display them:
foreach(range(1, $totalNumberOfPages) as $pageNumber) {
echo '' . $pageNumber . '';
}

PHP Pagination-related MySQL query issue

I'm trying to do 2 things.
1) Get the amount of rows in this query
SELECT
COUNT(*)
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
As you can see that is no problem ^^
2) Determine the number within the range of rows that is returned by id
Ex: ID 765 is Item 4 of 7 where column_1 = 152 and column_3 = 42
Does anyone have any basic solutions to this problem with almost pure MySQL? I'd like to avoid iterating through all the rows and setup a counter to increment until it matches current id like this:
$sql = '
SELECT
*
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
';
$query = mysqli_query($sql);
$current_id = 2523;
$i = 1;
while ($row = mysqli_fetch_assoc($query)) {
if ($row['id'] == $current_id) {
$current_position = $i;
}
$i++;
}
print 'Current position in range is: '. $current_position;
Also please don't worry about the actual syntax, I won't be using this exact script, but you get the logic that I'd like to avoid using. If anyone has a better solution, please let me know. Thanks in advance!!

how to get a specific id within 5 rows in a paging query in Mysql

I have a function in php I use it for paging it is like this :
$query = "SELECT id,
FROM table
ORDER BY id ASC
LIMIT $offset,5";
this work fine but what I want is to get the page that contain id number let say 10 and with it the other 4 rows, I want it to return something like this:
7,8,9,10,11,12 -> if I give it id number 10.
25,26,27,28,29 -> if I give it id number 26 and so on.
like it would return the 5 rows but I want to know how to set the offset that will get me
the page that have the 5 rows with the specified id included.
what should I do like adding where clause or something to get what I want!
Notice that the IDs in your table won't be consecutive if you delete some rows. The code below should work in such conditions:
$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);
$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Try something like this
//but for pagination to work $page should be $page*$limit, so new rows will come to your page
$limit = 5;
$start = ($page*limit) -2; // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values
$query = "SELECT id,
FROM rowa
ORDER BY id ASC
LIMIT $start,$limit";

Memory problems while copying data from one mysql table to another

I need to fetch, convert and then insert 4 000 000 rows into another table.
Needles to say, a memory exhausted error kicks in after 300 000~ entries. After every loop allocated memory increases by exactly 160 bytes.
I know that using mysql_unbuffered_query() would be possible, although it forces me to fetch all result rows before I can execute another query, which ends up in memory exhausted error again. So, what's the best way to do this in a single run?
mysql_connect($host, $user, $password);
mysql_select_db($db);
$getOldData = mysql_query("
SELECT *
FROM players_online
ORDER by id ASC
");
$numRows = mysql_num_rows($getOldData);
for ($i=0; $i < $numRows; $i++) {
$oldData = mysql_fetch_assoc($getOldData);
$hour = explode(':', $oldData['hour']);
$quarters = $hour[0] * 4 + $hour[1] / 15;
$update = mysql_query("
INSERT INTO players_online_2 (world_id, players_online, quarters_past_midnight, date)
VALUES (
'".$oldData['world_id']."',
'".$oldData['players_online']."',
'".$quarters."',
'".$oldData['date']."'
)
ON DUPLICATE KEY UPDATE
world_id='".$oldData['world_id']."',
players_online='".$oldData['players_online']."',
quarters_past_midnight='".$quarters."',
date='".$oldData['date']."'
");
if (mysql_error()) {
echo mysql_error();
die();
}
echo memory_get_usage().PHP_EOL;
}
MySQL Workbench will let you export the old database and import it into the new location.
With that said though, if you want to do this in PHP, you should probably not return the entire table in one shot. You could use LIMIT and OFFSET to split the query into pages, and then execute one page at a time. Something like this:
for ($i = 0; $i < $Limit; $i++)
{
// SELECT * FROM players_online ORDER by id ASC LIMIT 1000 OFFSET ' . $i
}
You can do this in a single query, something like:
INSERT INTO players_online_2 (world_id, players_online, quarters_past_midnight, date)
select world_id, players_online, quarters_past_midnight, date
FROM players_online po
ORDER by id ASC
ON DUPLICATE KEY UPDATE
world_id = po.world_id,
players_online = po.players_online,
quarters_past_midnight = po.quarters_past_midnight,
date = po.date;

Php lottery issues multi winner problems

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

Categories