开发者

How to 'really' detect integers from DB?

开发者 https://www.devze.com 2023-03-21 04:59 出处:网络
I\'m trying to save some code with the following. I\'ve an object with variables named the same as table rows so I could create an insert like this one:

I'm trying to save some code with the following. I've an object with variables named the same as table rows so I could create an insert like this one:

$query = "INSERT INTO table ";
        $columns = '(';
        $values = 'VALUES (';
        foreach ($this as $var => $value){
            if ($value){
                $columns .= $var.', ';
                if (!is_int($value))
                    $value = '\''.$value.'\'';
                $values .= $value.', ';
            }
        }
        $columns .= ')';
        $values .= ')';
        $columns = str_replace (', )', ')', $columns);
        $values = str_replace (', )', ')', $values);
        $query .= $columns." ".$values;

But every single 开发者_运维问答variable is detected as string and that's not true in all fields as you may imagine.

Does anyone have a solution?


Here's how I would write it:

<?php
$canonical_columns = array_flip(array("column1", "column2", "column3"));
$columns = array_keys(array_intersect_key($canonical_columns, (array) $this));
$params = join(",", array_fill(0, count($columns), "?"));
$columns = join(",", $columns);
$query = "INSERT INTO table ($columns) VALUES ($params)";
$stmt = $pdo->prepare($query);
$stmt->execute(array_values($this));

Stop concatenating fragments of strings to form SQL.

Use PDO, and use parameters for values.

Allowlist column names by comparing inputs to known, valid column names.


It appears as if you numbers are in fact strings. Try to use is_numeric() instead of is_int(). If this ain't enough you can cast the string to an integer and then check for != 0.


You may insert numbers in quotes too, as strings. This will not create an error.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号