PHP if runs twice and generates duplicate records to the MySQL database

I am writing a little piece of code for the one game where users can bid and the biggest bid wins the round (like the auction). There is a 1-minute timer and when it ends, some actions occur. I will write all the details below.

Timer script:

$auctionTimer = 1;

$target_time = strtotime('+' . $auctionTimer .  'minutes', strtotime($r1['date']));
$current_time = time();
$seconds_left = $target_time - $current_time;
$minutes_left = floor($seconds_left / 60);

if (strlen($minutes_left) != 2) {
  $minutes_left = sprintf("%02d", $minutes_left);
}  

$seconds_left -= $minutes_left * 60;
$seconds_left = floor($seconds_left);

if (strlen($seconds_left) != 2) {
  $seconds_left = sprintf("%02d", $seconds_left);
}

Something is bad with the if ($current_time > $target_time && $ragr1['count'] >= 1) { check:

$stmt1 = $pdo->prepare("SELECT id, user_id, user, bid, date FROM 
    tb_auction_bids ORDER BY id DESC");
$stmt1_while = $pdo->prepare("SELECT id, user_id, user, bid, date FROM 
    tb_auction_bids");
$stmt3 = $pdo->prepare("SELECT id, user_id FROM tb_auction_winners ORDER BY 
    id DESC LIMIT 1");
$stmt11 = $pdo->prepare("SELECT id, user_id, user FROM tb_auction_bids ORDER 
    BY id DESC LIMIT 1");
$stmt12 = $pdo->prepare("TRUNCATE TABLE tb_auction_bids");

$agr1 = $pdo->prepare("SELECT COUNT(id) AS count FROM tb_auction_bids");
$agr2 = $pdo->prepare("SELECT SUM(bid) AS sum FROM tb_auction_bids");


$stmt1->execute();
$stmt1_while->execute();
$stmt3->execute();
$stmt11->execute();

$agr1->execute();
$agr2->execute();

$r1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$r3 = $stmt3->fetch(PDO::FETCH_ASSOC);
$r11 = $stmt11->fetch(PDO::FETCH_ASSOC);

$ragr1 = $agr1->fetch(PDO::FETCH_ASSOC);
$ragr2 = $agr2->fetch(PDO::FETCH_ASSOC);

if ($current_time > $target_time && $ragr1['count'] >= 1) {
  $stmt9->execute(array(
    ':user_id' => $r11['user_id'],
    ':user' => $r11['user'],
    ':win' => $ragr2['sum']
  ));
  $stmt6->execute(array(
    ':win' => $ragr2['sum'],
    ':user_id' => $r1['user_id']
  ));
  while ($r1 = $stmt1_while->fetch(PDO::FETCH_ASSOC)) {
    $stmt7->execute(array(
        ':user_id' => $r1['user_id'],
        ':aukciono_id' => $r3['id'],
        ':user' => $r1['user'],
        ':date' => $r1['date'],
        ':bid' => $r1['bid']
    ));
  } to
  $stmt12->execute();
}

I guess I should not post PDO queries because the problem is not about SQL, it is about PHP. If you are not in this page (…/auction, e.g.), when the 1-minute timer ends, it does nothing at all. You have to go again to the …/auction, e.g., to get a reward. Should I use JavaScript to check if the timer ended and then execute the file?

This is how it looks like (video):
https://www.youtube.com/watch?v=_CZcnd3RTNw

Also, I get

“SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘post’
cannot be null” error and I looked into this thread:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘post’ cannot be null

but it did not help. The $r1['aukciono_id'] is defined also as another variables but only the $r1['aukciono_id'] gives an error.

if ($current_time > $target_time && $ragr1['count'] >= 1) { should run only once but it runs twice and generates duplicate MySQL records. Am I doing something bad with PDO or PHP? Maybe it is because of that PDO error? Help me, please.


Source: stackoverflow-php

Why its not displaying current time zone?

I am trying to add parameter in query which passes indian time zone to mysql database server.But when i am passing this query it shows 0000-00-00 00:00:00 in my table.
I am using hostinger php my admin database server.
Please help me to solve this.

<?php


include 'confi.php';

 date_default_timezone_set('Indian/Maldives');

    $email = isset($_POST['email']) ? mysqli_real_escape_string($conn,$_POST['email']) : "";
    $today = date("d/m/Y h:i:s A");

    $sql ="INSERT INTO `i_order` (`ID`, `email`,`date`) VALUES (NULL, '$email', '$today');"; 

    $qur = mysqli_query($conn,$sql);
    if($qur){
        $json = array("status" => 1, "msg" => "success!");
    }else{
        $json = array("status" => 0, "msg" => "error!");
    }

@mysqli_close($conn);

/* Output header */
    header('Content-type: application/json');
    echo json_encode($json);


?>


Source: stackoverflow-php

PHP Form to delete records in mySQLi when displaying then in a table

I’m making a system to display pages in the system in a table and one of the columns is the action column giving people the option to delete the page. I did this:

listpages.php

<?php
$sql = "SELECT * FROM Pages";
$result = $conn->query($sql);
if ($result) {
    while($row = $result->fetch_assoc()) {
        $pages[] = array_map('htmlspecialchars', $row);
    }
}
// PHP is finished now, here's the HTML
?>
      <form method="post" action="utils/delpage.php">
      <table>
        <thead>
          <tr>
              <th>Page Name</th>
              <th>Page Type</th>
              <th>Registered on</th>
              <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($pages as $page):?>
          <tr>
          <input type="hidden" name="targetid" value="<?= $page['id'] ?>"></input>
            <td><?= $page['pagename'] ?></td>
            <td><?= $page['pagetype'] ?></td>
            <td><?= $page['regdate'] ?></td>
            <td><input type="submit" value="delete" class="red-text material-icons tooltipped" data-tooltip="Delete"><td>
          </tr>
        <?php endforeach ?>
        </tbody>
      </table>
      </form>

delpage.php

<?php 

include ('../../php/db.php');


$id = $_POST['targetid'];
$target = htmlentities($id);

$stmt = $conn->prepare("DELETE FROM Pages WHERE id = (?)");
$stmt->bind_param("i", $page);

$page = $target;
$stmt->execute();


?>

This partially works: I get the trash icon I set to delete records. The problem is, when I click it, it will always delete the last record instead of the record it was said to delete. This is a problem, an not how it was really supposed to work. I don’t see why it’s doing this as the id is being “displayed” the same way the other information is. I searched SO for an answer but nothing worked and I didn’t see many options but creating a question. Any help?

Thanks in advance


Source: stackoverflow-php

MySQL / SQL PHP Error [duplicate]

This question already has an answer here:

$sql = "INSERT INTO website (id, username, password, email, timestamp, balance, rank, banned, color, ts3, minecraft, 'ip')VALUES ('', '$username', '$pwsalt', '$email', '$timestamp', '0', '1', '0', 'black', 'unknown', 'PedoBear', '$ip')";

Result:

Error: INSERT INTO website (id, username, password, email, timestamp, balance, rank, banned, color, ts3, minecraft, ‘ip’)VALUES (”, ‘FlareCO’, ‘ilovepokemongoeveryday’, ‘admin@customdomain.co’, ‘1492769557’, ‘0’, ‘1’, ‘0’, ‘black’, ‘unknown’, ‘Pikachu’, ‘125.558.95.254’)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ”ip’)VALUES (”, ‘FlareCO’, ‘ilovepokemongoeveryday’, ‘admin@customdomain.co’, ‘1492769557’ at line 1

What i need to fix ?


Source: stackoverflow-php

List all the users with the count of drivers they registered

i have tow models Userand Driver the user can register any number of drivers drivers

in drivers table i have agent_id, i want to list all the users with the count of the drivers they registered

in my Usercontroller i want to get the count of the drivers registered by the agents

public function index(Request $request) 
{
    $users = User::all();

    $registration_centers = RegistrationCenter::all();

    $drivers_registered = Driver::where('agent_id' , $agent_id)->count();  //something like this but i don't have agent_id to query with

    return view('agents', compact('users', 'registration_centers', drivers_registered));
}

thank you


Source: stackoverflow-php

php/sql – Insert Data into Table with PHP (Bootstrap Form, if that makes a difference)

Bottom line: I don’t know what the hell I’m doing. I just want this comment box to submit information to my database. Let me show you what I got.

<form method="POST" action="post.php" style="font-
 size:200%;padding:50px">
<label for="comments">Comments:</label>
<textarea class="form-control" placeholder="How can I improve?" 
 style="background-color:#fff4c9;border-radius:15px;width:100%;" 
 name="comments" rows="5" id="comments" value=""></textarea> <br>
<button type="submit" class="btn btn-default">Share Your Ideas</button>
</form>`

and then my php i guess????

<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$username = "id1403626_wp_4764008ac42f7398450c24184e47c38a";
$password = "Marshall2";
$dbname = "id1403626_wp_257ecd760342ffcefce424435ed4e776";
//Collect Value of Input Field
$name = $_POST['comments'];
$timestamp = date('Y-m-d H:i:sa');

//Create connection
$connect = mysqli_connect($servername, $username, $password);

//Check connection
if ($connect->connect_error) {
die("So here's the problem...:".$connect->connect_error);
}
//Select Database
mysqli_select_db($connect,$dbname)
or die("Whoops! Can't find that pesky database!");
//Insert Data Query
$sql = "INSERT INTO `Comments`(`comments`, `date`) VALUES ($name, 
$timestamp)";
//What should happen
$result = mysqli_query($connect, $sql);

if($result){
echo 'thank you for your feed back';
}else {
echo "Fuck man I can't code this shit right. If you have a comment email 
it to me at philobythekilo@gmail.com I'ma get this shit working one of 
these days.";
}
}
?>

I just cannot find what I am doing wrong. Help a sista out, please!


Source: stackoverflow-php

Selecting Data from Multiple rows and sorting it

[   id    -   title   -   content  -   class]
[    1    -     t1    -     p1     -     1  ]
[    2    -     t2    -     p6     -     1  ]
[    3    -     t3    -     p5     -     2  ]
[    4    -     t4    -     p8     -     3  ]

For this table, How can i use 1 query to SELECT all classes DISTINCTLY to become this HTML

<label>Class: 1</label>
t1, p1
t2, p6
<label>Class: 2</label>
t3, p5
<label>Class: 3</label>
t4, p8

I really can’t figure out a way to SELECT all the data and sort it at the same time at all.


Source: stackoverflow-php

Optimize SQL Statement: Select multiple values

I would like to decrease my SQL querys. Here you can see an example of my table:
enter image description here

This statement returns me the amount of fields (0-3) I have:

SELECT COUNT(meta_key) FROM `fWR6qIN_postmeta` Where meta_key like 'product_shops_%_price' AND (post_id = 7951)

In this case I get a 4. So I have values from the field 0 to 3. For each number I need product_shops_%_price, product_shops_%_price_old, product_shops_%_shop and product_shops_%_link. So, 4 * 4 = 16 values.
Now I want to reduce my query from 4 to 1 query. Previously I asked every 4 fields separated. So I got 4 values for 0, for values for 1, and so an..

My Plan Now is the optimize that SQL Statement and Select all 16 values at once. Does anyone has a plan how I can do that?

And further, it would be very nice if I can pack all values which contains a 0 in a array, all which contains a 1 in a array and so on… So I can iterate through them easily.

I would be very grateful about help!
Greetings!


Source: stackoverflow-php

Fiverr and the way it works

I have a question of a more general nature, not a specific programming “issue”.

I’m learning about web development and I stumbled upon a website called Fiverr.
Basically it’s a platform for freelancers where they can create accounts and offer any service you can imagine.
These services are called “gigs”.
Obviously this is very appealing to customers so the website is doing great.
Why I’m interested in this type of website is because it is different than a conventional “e-commerce” web page.
It actually lists “gigs” on the homepage depending on the users that created those gigs.

Long story short, does anyone have any insight on how you could do that?
I reckon it’s done either in js/php, but how exactly would you do it?
Also, how do you think Fiverr itself was made?
Using CMS or coded from scratch?

Anyway, thanks and sorry if this question doesn’t belong in here, I just thought this community would give the best answers.


Source: stackoverflow-php

Laravel – Get row that has today between begin and end

I have a table that has two dates fields, begin and end.

I’m trying to get all rows that have begun but not yet ended. and if today is less than begin, they shouldn’t be included. and if today is grater than end they shouldn’t be included.

I’m using laravels eloquent. Here is what i’ve tried

$now = CarbonCarbon::now();

$promos = AppModelsLivePromo::
    where("begin", "<=", $now)
    ->where("end", ">=", $now)
    //Other conditions
    ->get(); 

This seemingly work, but it also selects rows that are greater have already ended.
How can i make this work as i expect?


Source: stackoverflow-php