0

Never seen this before. Was unable to find and explanation and I saw it the other day in a code, e.g.:

    $statement = $db->prepare("insert into table (col1, col2, col3) values (?, ?, ?)");
    $data = array((string) $var1, (string) $var2, (string) $var3);
    $statement->execute($data);

See this (string) part? Anyone to shed some light on it, please?

4
  • its not actually about prepared statement, its just type cast for the variable. here's the entry from the manual php.net/manual/en/language.types.type-juggling.php
    – Kevin
    Commented Feb 28, 2019 at 9:53
  • 1
    Sorry for the newb question. This answers it. Thanks!!
    – lion
    Commented Feb 28, 2019 at 9:54
  • 1
    Possible duplicate of PHP typecasting
    – Qirel
    Commented Feb 28, 2019 at 9:56
  • The string cast looks unnecessary though. All values are treated as PDO::PARAM_STR Commented Feb 28, 2019 at 10:13

3 Answers 3

1

It means everything that is written in $var1 and the others is converted to a String so the Programm can handle the input without getting an error.

1

This is a simple cast , here in the code , while the query is a string , so the (string) make sure that you are manipulating String , here is the PHP DOC:

(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL

http://php.net/manual/en/language.types.type-juggling.php

Example:

$int = 4;
$string = (string)$int; 
echo gettype($int); // output snteger
echo gettype($string); // output string

In general , the meaning of type casting is to use the value of a variable with different data type.

2
  • The even better answer! Thanks!!
    – lion
    Commented Feb 28, 2019 at 9:57
  • 1
    Enjoy the great PHP Commented Feb 28, 2019 at 10:01
0

You can bind parameter

$stmt = $conn->prepare("INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt->execute();

Type specification chars

i corresponding variable has type integer

d corresponding variable has type double

s corresponding variable has type string

b corresponding variable is a blob and will be sent in packets

2
  • 1
    you can also do that step in the execute.. " input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR. " source Commented Feb 28, 2019 at 10:01
  • 2
    this interface is mysqli, the OP is using PDO
    – Kevin
    Commented Feb 28, 2019 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.