Looping with database?

hi guys i am beginner in php can you give me an idea how to construct?

i have a button when i click button, the value of count will increase to plus 1.

image

thanks in advance :slight_smile:

First learn what query is needed to update the count column then you can implement that into your Php code.

@benanamen thanks for reply ill try to create a code this looks like.

<?php
$connect = mysqli_connect('localhost', 'root', '', 'test2');
    if(isset($_POST['submit'])) {
        $count= mysqli_real_escape_string($connect, $_POST['count']);
        $var = "UPDATE name SET count='$count' WHERE id=1";
        $result = mysqli_query($connect, $var);
        for( $result = 0 ; $result <= 9 ; $result++ )
        {
            echo $result . '<br />';
        }
    }
?>

this is my html

<!DOCTYPE html>

<html>
    <head>

    </head>

    <body>
        <form action="index.php">
            <input type="text" name="count" class="text" value="1">
            <input type="submit" name="submit" class="text">
        </form>
    </body>
<html>

There is no firstname in your form. Is it just the count you want to update? You are also missing the form method.

yes i need to update the count when i click the button it will loop to plus 1. then the next click is plus 1 = 2.

If all you are doing is updating the count when the button is clicked you don’t need anything more than this…

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//UPDATE name SET count = count + 1 where id = 1
}
?>
<form method='post'>
<input type="submit" name="submit">
</form>
1 Like

@benanamen thanks a lot it works you may closed this topic :slight_smile:

Hi @denmarkdelpuso108 and welcome to the SP Forum.

Try adding these validation tests to the top of the PHP pages:

<?php 
// PHP 7 SPECIFIC:
// FAILS FAST FOR ANY ERRORS OR WARNINGS ON THIS PAGE ONLY
   declare(strict_types=1);  // MUST BE CALLED FIRST 

// APPLIES TO THIS FILE AND ALL INCLUDED AND REQUIRED FILES
   error_reporting(-1); // MAXIMUM ERROR REPORTING
   if( $DEBUG=TRUE )  // CHANGE TO FALSE WHEN ONLINE
   {
     ini_set('display_errors', '1'); //  
   }

// DATABASE VALIDATION
// https://phpdelusions.net/mysqli/error_reporting 
   mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
   YOUR ORIGINAL SCRIPT FOLLOWS HERE
*/  

Also use these Free Online Testers:

Copy and search for any errors or warning and raise a topic here if the validation still fails after applying fixex.

The debug line is wrong. You are using assignment instead of equality. And even if it did have equality, it is still redundant since the IF function is already a truthie check. Error reporting settings should be set in the ini file not in the script.

1 Like

this is my code working.

<!DOCTYPE html>

<html>
    <head>
    </head>
    <body>
        <form action="index.php" method="POST">
            <input type="hidden" name="count" class="text" value="1">
            <input type="submit" name="submit" class="text">
        </form>
    </body>
<html>

<?php

$connect = mysqli_connect('localhost', 'root', '', 'test2');


    if(isset($_POST['submit'])) {
        $count = mysqli_real_escape_string($connect, $_POST['count']);

        $var = "UPDATE name SET count=count + 1 WHERE id=1";
        $result = mysqli_query($connect, $var);
        header('location: next.php');
    }

?>

The count input and the mysqli escape is pointless. You aren’t even using it. You will generally want to kill the script after a header redirect since the script will keep running. In this case it doesn’t matter since no code follows it. Making your script depend on the name of a button to be submitted will completely fail in certain cases. I already showed you what to.

1 Like

Actually the statement is correct, valid and does not raise any errors or warnings with declare(strict_types=1).

The idea was to prevent having to declare $DEBUG on an additional line.

   if( $DEBUG=TRUE )  // CHANGE TO FALSE WHEN ONLINE
   {
     ini_set('display_errors', '1'); //  
   }

Note the trailing comment about toggling the `$DEBUG value.

Error reporting settings should be set in the ini file not in the script.

Yes I agree but for quick and dirty tests the supplied script works fine :slight_smile:

1 Like

@denmarkdelpuso108.Next to the error reporting as described by @John_Betong There are a couple of things you should adjust.

As @benanamen allready mentioned and showed you in post # 8. You should use:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

rather then

if(isset($_POST['submit'])) {

Both can be used but it’s better not to rely on clicking a button. After the REQUEST_METHOD’ you should do some sort of checking

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	if (isset($_POST['count'])) {
		// update query
		header('location: next.php');
		exit();
	} else {
		// $_POST['çount'] doesn't exist
	}
} else {
	// is not a post request redirect back to original page
	header('location: previous.php');
}

hi @donboe noted thanks :slight_smile:

i have a another problem i need to delete the data row in table1 and all deleted data will transfer to another the table2. do you have any idea how to do it?

this is my code.

<?php
require('db.php');

$id=$_REQUEST['id'];

$var = "INSERT INTO eliminated_tb (name, score) SELECT name, score FROM new_record";
$result = mysqli_query($con,$var);


$query = "DELETE FROM new_record WHERE id=$id";
$result2 = mysqli_query($con,$query);
header("Location: index.php");
?>

@denmarkdelpuso108… I don’t know your tables structure ofcourse but shouldn’t you use the $id in the insert query as well?

 INSERT 
   INTO `eliminated_tb` (`name`,`score`)
 SELECT `name` 
      , `score`
   FROM `new_record`
  WHERE `id` = $id;
  
 DELETE
   FROM `new_record`
  WHERE `id` = $id;

Also consider to use prepared statements within your queries.

 $var	=	"INSERT
               INTO `eliminated_tb` (`name`, `score`)
			 SELECT `name`
			      , `score`
			   FROM `name`
			  WHERE `id` = ?";
			  
 $stmt  = $mysqli->prepare($sql);
 $stmt->bind_param('s', $id);
 $stmt->execute();

So instead of using the variable in the Where clause you use a question mark parameter
Prepared statements making your queries way safer against attacks

This logic is wrong. What is the real problem you are trying to solve.

Then that is a bad idea. It will confuse every programmer that ever looks at it and maybe even you down the road. All of a sudden you have the variable $DEBUG that just pops up out of nowhere and is never used and then purposely doing an assignment within an if function when the expected practice is to do a comparison and all for the sake of not having one more line that anyone and everyone would expect. That is just a really bad practice. Just because something “works” doesn’t mean you should do it.

If you reeelly want to avoid the “extra” line then you can do the following which will not confuse anyone and is even less typing.

   if( TRUE )  // CHANGE TO FALSE WHEN ONLINE
   {
     ini_set('display_errors', '1'); //  
   }
// FAILS FAST FOR ANY ERRORS OR WARNINGS ON THIS PAGE ONLY

Actually the statement is correct, valid and does not raise any errors or warnings

Your code comment seems to imply you think strict_types is for catching errors and warnings. That is not what it is for.

Php Manual

In strict mode, only a variable of exact type of the type declaration will be accepted,

I don’t see you declaring any types so having strict_types enabled is doing nothing in this case and makes it irrelevant that the code “does not raise any errors or warnings” because you have it enabled. It also will not make it “fail fast”.

hi @donboe i have an error. and thanks to @benanamen

Notice : Undefined variable: mysqli in C:\xampp\htdocs\rrd\delete.php on line 16
Fatal error : Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\rrd\delete.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\rrd\delete.php on line 16

<?php
require('db.php');
$id=$_REQUEST['id'];

$var = "INSERT INTO eliminated_tb ('name', 'score') SELECT 'name', 'score' FROM new_record WHERE id=?";
$result = mysqli_query($con,$var);

$stmt  = $mysqli->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();

$query = "DELETE FROM new_record WHERE id=$id";
$result2 = mysqli_query($con,$query);
header("Location: index.php");
?>

and what is the purposed of this code :slight_smile:

$stmt  = $mysqli->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();

this is my table eliminated.

and this is my table new record.

Your comment strongly suggests you are just copy/pasting code you find on the Internet. I highly recommend you actually learn what you are doing. Do yourself a favor and spend some time learning PDO instead of Mysqli. Here is a tutorial to get you going.
https://phpdelusions.net/pdo

2 Likes