Search code examples
phpjquerypostgresqluser-input

How do I use a form variable in my php psql query?


So basically right now I have this:

<form action="pgsqltest.php" method="get">
    How many rows of data?: <input type="number" name="rod"><br>
    <input type="submit">
</form>

<?php
require_once('C:\wamp\www\pgsqlconnect.php');

    $query = 'SELECT * FROM db.logs;';
    $result = pg_query($query) or die('Query failed: ' . pg_last_error());

    $query = 'SELECT * FROM db.logs LIMIT {$_POST['rod']};';
    $result = pg_query($query) or die('Query failed: ' . pg_last_error());

What I'm trying to do is get a number from a user named "rod", and then I want to pass it into my SQL query so that they can get whatever limit or number of rows in the database table they want. Whenever I do this code, I get this error:

Parse error: syntax error, unexpected 'rod' (T_STRING) in C:\wamp\www\pgsqltest.php on line 107

So obviously it's a syntax error, but I can't figure out how to actually pass the variable to the query. Whenever I do

 echo $rod;

I get an error saying

Undefined variable: rod

So pretty much what I know is that the form name is not an actual variable. How will I go about using user input into my SQL queries?

Doing this: $query = "SELECT * FROM data.epf_logs LIMIT {$_POST['rod']};";

gave me two errors: First:

 Notice: Undefined index: rod   

Second:

 Warning: pg_query(): Query failed: ERROR: syntax error at or near &quot;;&quot; LINE 1: SELECT * FROM data.epf_logs LIMIT ; ^

Solution

  • I'd suggest something like this:

    <form action="pgsqltest.php" method="get">
        How many rows of data?: <input type="number" name="rod" />
        <br />
        <input type="submit" name="submit" /> <!-- Add a name to allow us to check if sent -->
    </form>
    

    Added a name to your submit to check with

    //Setup the connection
    $conn = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
    
    require_once('C:\wamp\www\pgsqlconnect.php');
    //Check if POST has been sent
    if (isset($_POST['submit']))
    {
    
        $query = "SELECT * FROM db.logs;";
        //Use connection in all pg_* function calls
        $result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
    
        //Set rod to be an int of 0 if not set or a safe vause of $_POST['rod'] if set
        $rod = (int)(isset($_POST['rod']) ? pg_escape_string($conn, $_POST['rod']) : 0);
        $query = "SELECT * FROM db.logs LIMIT {$rod};";
        $result = pg_query($conn, $query) or die('Query failed: ' . pg_last_error());
    }
    

    I saw from php.net, that pg_* functionality has 2 params, $connection_stringand $query in that order, so using the connection (IMO) is a must, check this and this for details

    I'm not gonna guarentee this'll work. Just a pointer.