I modified this code from somewhere but I am not sure if I am doing it correctly,
I use method to insert data into database,
# insert or update data
public function query($query, $params=array())
{
try
{
$stmt = $this->connection->prepare($query);
$params = is_array($params) ? $params : array($params);
$stmt->execute($params);
return true;
}
catch (PDOException $e)
{
# call the get_error function
$this->get_error($e);
}
}
Then I just need to call it like this,
$sql = "
INSERT root_countries_cities_towns (
tcc_names,
cny_numberic,
tcc_created
)VALUES(
?,
?,
NOW()
)";
$pdo->query($sql,array('UK','000'));
It works fine perfectly! but I don’t understand what this line does – can someone explain please?
$params = is_array($params) ? $params : array($params);
I thought I have to use bindParam to bind the parameters first, but it seems that I don;t have to anymore with is method – is it safe and secure then??
Does it meant that I don’t have to prepare the query in this way anymore?
$sql = "
INSERT root_countries_cities_towns (
tcc_names,
cny_numberic,
tcc_created
)VALUES(
:name,
:numberic,
NOW()
)";
and forget about this binding?
$stmt = bindParam(':name','UK', PDO::PARAM_STR);
$stmt = bindParam(':numberic','000', PDO::PARAM_STR);
Thanks.
I guess that’s pretty much PHP syntax question rather than PDO one.
is a shortland (called ternary operator)) for
which I’d rather wrote as
which is pretty self-explanatory and can be read almost in plain English:
That’s why I hate ternary operator (and lambdas) and always avoid it’s use. It makes pretty readable code into a mess. Just out of programmer’s laziness.
To answer your other questions,
Who said that? You’re preparing it all right in your code, check it again.
that’s true.
execute($params)is just another way to bind variables.