-3

Trying to create a simple cumulative addition script in PHP (or JS):

1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page

2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page

Repeat …….

Example: the mantra counter at garchen.net

Below is the code I have so far In Index.php:

<form method="post" action= "process-mantra-form-ami.php" >
    <p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
    <div style="margin-left: 20px;">
        <p>OM AMI DEWA HRI</p>
        <input type="text" name="accumulation" size="10" maxlength="6">
        <input type="submit" value="Submit Your Mantra" name="B1"><br>
        <span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
        <p></p>
    </div>
</form>

I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?

You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!

PROCESS-MANTRA-FORM-AMI.PHP code below

<?php 

// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);

// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
  echo "Database my_db created successfully";
} else {
  echo "Error creating database: " . mysqli_error($con);
}

// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
  echo "Table mantras created successfully";
} else {
  echo "Error creating table: " . mysqli_error($con);
}

// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");

}

mysqli_close($con);


?>

<div>   
    <h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>

    <p>Remember to dedicate your merit.</p>

    <p><a href="index.php">Return to the main site</a></p>

</div>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Mark
  • 1
  • 3
  • What error did SQL tell when running this `$sql="INSERT INTO Mantras (Num INT) VALUES ('$num')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }` – Funk Forty Niner Oct 12 '14 at 03:12
  • May I ask why you're creating the db over and over again? I mean, it looks to me like if you use this to process your data, it'll try to create a new db everytime? – icecub Oct 12 '14 at 03:16
  • 1
    [ohh.... sql injection........](http://xkcd.com/327/) – gloomy.penguin Oct 12 '14 at 03:35
  • Fred- I have not run it yet – Mark Oct 12 '14 at 03:40
  • icecube-so are you suggesting that I combine my three $sql statements into one? – Mark Oct 12 '14 at 03:42
  • Paul - I didnt know that. Next time I will update rather than repost. – Mark Oct 12 '14 at 03:43
  • The friendly guy in me just wants to write the script for you, but your code suggests that you won't know what to do with it because you don't even have a database in the first place. You have a lot to learn and comments aren't the best place to do that.. – icecub Oct 12 '14 at 03:43
  • No I don't suggest that. Normally you create your db first. Then you use PHP to communicate with it. For what you want to do, there shouldn't be any create database or table in your code at all. – icecub Oct 12 '14 at 03:50

1 Answers1

1

try this out... (sorry, bored tonight)

<?php  
$host = 'localhost';  // localhost:8888
$user = 'root';      
$pass = '';           // root
$dbnm = 'test'; 
$conn = mysqli_connect($host,$user,$pass,$dbnm)
            or die('Error ' . $conn->connect_error);    

// for testing.... so i can run the code over and over again and not 
// get errors about things existing and stuff 
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');     
run_statement($conn,"drop table    if exists `mantras`;",'cleared old table');   
run_statement($conn,"drop table    if exists `two_col_table`;",'cleared old table');            

// Create database
$sql  = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');   
if (!$err) $conn->select_db('my_db'); 

// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');  

if (!$err) {
   $sql  = 'insert into mantras (num) values ( ? )';
   $stmt = $conn->prepare($sql); 
   $stmt->bind_param('d',$num);   // d is for digit but s (string) would work too
   $num = 1; 
   $stmt->execute(); 
   $num = 2; 
   $stmt->execute(); 
   $stmt->close(); 
   echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully'; 

   // update database
   $sql = 'update mantras set num = num + 1';
   run_statement($conn,$sql,'Update database'); 
}


// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');  

if (!$err) {
   // demonstrating how to bind multiple values 
   $sql  = 'insert into two_col_tbl values ( ?, ? )';
   $stmt = $conn->prepare($sql); 
   $stmt->bind_param('ds',$num,$txt);   
   $num = 1; $txt = 'hello';
   $stmt->execute(); 
   $num = 2; $txt = 'world';
   $stmt->execute();  
   $stmt->close(); 

   // select statement
   $sql  = 'select num, txt from two_col_tbl';
   $stmt = $conn->prepare($sql); 
   $stmt->bind_result($db_num, $db_txt);
   $stmt->execute();  
   print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
   while ($stmt->fetch()) {
      print "<tr><td>$db_num</td><td>$db_txt</td></tr>"; 
   }
   print '<table>';
   $stmt->close(); 
} 

$conn->close();  


function run_statement($conn,$statement,$descr) { 
   if ($conn->query($statement)) 
        echo "$descr ran successfully"; 
   else echo "$descr failed: {$conn->error}"; 
   return $conn->error; 
} 
?>

<div>   
    <h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2> 
    <p>Remember to dedicate your merit.</p> 
    <p><a href="index.php">Return to the main site</a></p> 
</div>
gloomy.penguin
  • 5,833
  • 6
  • 33
  • 59
  • Upvoting this for all your hard work and the good laugh it gave me I desperately needed. Nice job! xD – icecub Oct 12 '14 at 05:51
  • Icecube -Yes I do have a lot to learn. Im trying! Thanks for your references, info and code. I'll study it and check it out. Thanks much. – Mark Oct 12 '14 at 14:41