Page 1 of 1

MYSQL query with a $_POST variable

Posted: Wed Sep 18, 2013 6:37 pm
by p0851035
Hello all,

I would be very pleased if someone could help me to resolve this problem:

I just want to select data in a DB after a form. Here is the code:

$req = $bdd->prepare('SELECT * FROM `nameoftable` WHERE `brand`=?');

$req->execute(array($_POST["brand"]));

while($donnees = $req->fetch()){"

The _POST variable is defined but it seems like it cannot be recognized as a string.
This manner works for numbers but not sentences. So Imagine there is the word "TURTLE" in my post variable it will not work but if a wrote: $req = $bdd->query('SELECT * FROM `nameoftable` WHERE `brand`= TURTLE');
then it will work.

Thank you very much for your Help :)

Re: MYSQL query with a $_POST variable

Posted: Wed Sep 18, 2013 7:19 pm
by p0851035
I think it is because there is a space after the entry in the db...
Someone can explain that?

Re: MYSQL query with a $_POST variable

Posted: Thu Sep 19, 2013 2:30 pm
by Christopher
p0851035 wrote:I think it is because there is a space after the entry in the db...
Someone can explain that?
Not sure about the space. Are you sure that you non-numeric values are quoted? "... WHERE `brand`= TURTLE" should give an error, whereas "... WHERE `brand`= 'TURTLE'" should work. You may need to set the data type for your prepared statement.

Re: MYSQL query with a $_POST variable

Posted: Tue Sep 24, 2013 5:09 am
by priyankagound
Try out with the below example.
I have used this code before in my application.

***** Please put code in PHP Code tags *****

Code: Select all

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

    //detect if we have errors or not
    $errors = false;
    $error_msg = "Error, please try again";

    //if we have no errors, do the SQL
    if (!$errors) {   

        $latin_name = $_POST['latin_name'];

        $stmt = $conn2->prepare("SELECT common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type, price, stock_level, fragrance, ultimate_height FROM rosename WHERE latin_name = ?");

        $stmt->bind_param('s', $latin_name);
        $stmt->execute();

        if ($result = $stmt->get_result()) {
            /* fetch associative array */
            echo "<form><input type='text' value='" . $result["common_name"] . "' name='common_name' />";
            echo "<input type='text' value='" . $result["variety_name"] . "' name='variety_name' /></form>";
            // i no I need to add more here..
            exit;
        }

        //put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
        require_once('footer.php');
        exit;
    }

    //if we do have errors, show the error message
    else {
        echo "<p>".$error_msg."</p>";
    }}

}

Hope this helps you.