Jump to content

adding 2 values together and inserting in to mysql


sixbeforewdawn

Recommended Posts

Hi

 

Sorry if this is a really simple question, I have looked round but can't a solution to my problem. If anyone can help or point me in the right direction

 

I have a html form which runs the below PHP script

 

<?php$con=mysqli_connect("localhost","username","password","mydatabase");// Check connectionif (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error();}$sql="INSERT INTO mytable (name, score,score2)VALUES('$_POST[name]','$_POST[score]','$_POST[score2]')";if (!mysqli_query($con,$sql)){ die('Error: ' . mysqli_error($con));}echo "Your Score has been added";mysqli_close($con);

?>

 

Which inserts the data in to MySQL without any problems :) But I'd like the code to add 'score' and 'score1' together and insert this in to MySQL.

 

I have tried adding

 

$total = score + score1;

$sql="INSERT INTO mytable (name, score, score2, total)VALUES('$_POST[name]','$_POST[score]','$_POST[score2]','$_POST[$total]')";

 

But it just inserts a 0

 

Cheers

Link to comment
Share on other sites

variables in php are preceeded by a dollar sign.

 

$total = score + score1;

should be

$total = $_POST['score'] + $_POST['score2'];

 

I believe it is good practice to set the $_POST array into variables though, so it can be this as well:

$score1 = $_POST['score'];

$score2 = $_POST['score2'];

$total = $score1 + $score2;

 

$_POST[$total] should just be $total

Edited by astralaaron
Link to comment
Share on other sites

variables in php are preceeded by a dollar sign.

 

$total = score + score1;

should be

$total = $_POST['score'] + $_POST['score2'];

 

I believe it is good practice to set the $_POST array into variables though, so it can be this as well:

$score1 = $_POST['score'];

$score2 = $_POST['score2'];

$total = $score1 + $score2;

 

$_POST[$total] should just be $total

Thank you so much for the help :D it's working great. And gives me a lot of help for future php scipts

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...