1

I have a pagination in my webpage. So I want to add a line to my query if I have a post from pagination:

$q="";
if(isset($_POST["inpi"])){
    $in = $_POST["inpi"];
    if(is_numeric($in)){
        $q = "and c.id < '$in'"; // add this to mysql
    }
    else{die("something is wrong!");}
}

So I can't use prepare statments here.

select k.user, c.id, c.from, c.sent, c.message, c.recd from chat c
inner join cadastro k on c.from=k.id
where `from`=? and `to`=? $q

notice the $q variable, it will have no value if post is empty or the and c.id < '$in'.

is it secure enought?

5
  • 1
    If you are verifying the input using is_numeric then I think you don't have to worry about sql injection in this case. Since for sql injection there must be some quotes and strings involved. Commented May 4, 2016 at 21:35
  • 2
    You absolutely can use prepared statements here. Are you using PDO? You can add something to the query string and the array used to hold the values at the same time. Commented May 4, 2016 at 21:42
  • @tadman I'm using mysqli Commented May 4, 2016 at 21:47
  • 2
    PDO does make it easier, but mysqli isn't impossibly hard. Commented May 4, 2016 at 21:48
  • 1
    Here's an example of doing it with mysqli that could be adapted. Commented May 4, 2016 at 21:54

1 Answer 1

2

You can always accumulate arguments as you go and build it out like this:

$query = "SELECT ... WHERE `from`=? AND `to`=?";
$binds = array("ss", &$from, &$to);

if (isset($_POST["inpi"])) {
  $query .= " AND c.id < ?";

  $$binds[0] .= "i";
  $binds[] = &$_POST["inpi"];
}

$stmt = $mysqli->prepare($query);

call_user_func_array(array($stmt, 'bind_param'), $binds);

I haven't tested this, but it's based on this code and may require some adjustments to work.

PDO's execute() function takes an array straight up, it's way easier to work with.

Sign up to request clarification or add additional context in comments.

1 Comment

oh, it is amazing! thank you very much for your help, friend!

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.