views:

29

answers:

1

A Submit button for a form located on my page triggers the code below, but I am unsure of how to save the numeric value of a textbox named 'amount' into a php variable which I can use in the below PDO query. I am unsure of the syntax. Thanks in advance!

     if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$amount = isset($_POST['amount']) ? $_POST['amount'] : null;
if (null != $amount) {

$user = 'user';
$pass = 'pass';
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
session_start();
$tablename = $_SESSION['MM_Username'];
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1', $tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
}
}

Removed db_select line and also have verified that the SESSION variable MM_Username is in fact set properly. Is there anyway SQL can spit back more detailed error reporting? When I run the code as it is above, I receive no errors, however, it simply does not work.

A: 

Edit: Totally revised answer with error reporting via Exception

session_start();
if (isset($_POST['MM_update']) && $_POST['MM_update'] == 'form1') {
    $amount = isset($_POST['amount']) ? $_POST['amount'] : null;
    if (null === $amount) {
        throw new Exception('Amount not set');
    }
    $user = 'user';
    $pass = 'pass';
    if (empty($_SESSION['MM_Username'])) {
        throw new Exception('Username table not set in session');
    }
    $pdo = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1', $_SESSION['MM_Username']);
    $stmt = $pdo->prepare($query);
    $stmt->bindParam('amount', $amount);
    $stmt->execute();
} else {
    echo 'Nothing to do';
}
Phil Brown
Ok will try these two possibilities and get back to you.
Parker
Finally got it Phil!! Form variable amount was not being set correctly due to having two forms with identical names on the same page. I cannot thank you enough for your help this evening. Have a great Night!!
Parker
FYI - The form "name" attribute is useless.
Phil Brown
While table name supposed to be secure, it's still very bad and highly dangerous practice to add data to the query this way. You lose all PDO benefits at once. I would check table existence with another query first. Or, even better, would not use named tables at all.
Col. Shrapnel