I have a class in PHP where I get a single record, I have two fields in the select :
public function buscar() {
$sql = "SELECT campo1, campo2 FROM tabla1 WHERE CONDICION limit 1";
$bd = new Conn();
$stmt = $bd->query($sql);
$row = $stmt->fetchAll();
return $row;
}
I want to assign the values of field1 and field2 to two variables:
$tabla = new Tabla();
$valores = $tabla->buscar();
echo $valores ["campo1"];
echo $valores ["campo2"];
But it shows me this message:
Notice: Undefined index: campo1
Notice: Undefined index: campo2
What am I doing wrong? The select only returns one record with two fields, so you shouldn't use Array.
fetchColumn
As its name indicates, it is used for one column (if there are several, it only obtains the first column). This method is useful for queries that return a single column, such as if you want to count the rows in the table.For several columns you can use the method
fetch
with any of thefeth_style
available ones .For example, if you use it with
PDO::FETCH_ASSOC
you it creates an associative arraycolumna => valor
Or for example if you use it with
PDO::FETCH_OBJ
is similar to the previous one, but you can use the object notation, much more intuitive and elegant:There are other fetch_style , but these are the ones that are usually used for this type of case.