1

Am trying to insert into two tables but get this error

Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`

below is my insert code

<?php

    session_start(); {



    //Include database connection details
    include('../../dbconnect.php');


$amount =  strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);



$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql)) 


$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql)) 

 {
    $_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
   header("location: PH.php");
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
}
?>

but when i do some thing like this it works

$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";

i just change the $field1amount to $field2amount

but i dont want it that way i want to also get the value of $field1amount and insert it

please any help will be appriciated, thanks

1
  • 2
    You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Specially since you're not escaping the user inputs at all! That would also solve your comma problem. Commented Feb 3, 2017 at 19:37

1 Answer 1

10

The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.

Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:

$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);

/*
    - the "s" below means string
    - NOTE you should still validate the $_POST value,
      don't just accept whatever is sent through your form - 
      make sure it matches the format you're expecting at least
      or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();
Sign up to request clarification or add additional context in comments.

1 Comment

My recommendation would actually be to use PDO if at all possible. See php.net/manual/en/pdo.connections.php to connect to a database and php.net/manual/en/pdo.prepared-statements.php to prepare statements, bind parameters, and execute the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.