Josiah L. Josiah L. - 5 months ago 21
SQL Question

PHP PDO MySQL array only returning column names

I am having an issue with my prepared SELECT result array not holding the actual column values. I know how to get data from an sql database using Java, however I am having issues with PHP PDO. I am connected to a remote AWS database that I know works. Here is the code:

$conn = new PDO($dsn, $username, $password);
//echo "Test";


Here I want to get all the column's data

$sth = $conn->prepare("SELECT 'id', 'short-des', 'full-des', 'image-urls', 'date-created' FROM projects");
$sth->execute();


I have placed PDO::FETCH_BOTH, PDO::FETCH_ASSOC, PDO::FETCH_COLUMN. The result at the end of this post is a result of me leaving the fetchall() blank. When I insert any of the PDO::styles no values are returned. I have done other scenarios such as using var_dump along with the styles in the fetch statement which provide actual results, BUT no actual values that the columns contain.

$row = $sth->fetchAll();

echo "<br>" . $row[0] . "<br>";
echo "<br>" . $row[1] . "<br>";

$column1 = $row[0];
$column2 = $row[1];

for($i = 0; $i < 5; $i++){
echo " " . $column1[$i];
$var = $column1[$i];
echo " = " . $var . " , ";

}
for($i = 0; $i < 5; $i++){
echo " " . $column2[$i];
$var = $column2[$i];
echo " = " . $var . " , ";
}


This is the resulting text:


64-bitPDO is available

Array

Array
id = id , short-des = short-des , full-des = full-des , image-urls = image-urls , date-created = date-created , id = id , short-des = short-des , full-des = full-des , image-urls = image-urls , date-created = date-created , Connected successfully


I'm guessing its some stupidly simple reason that it is not showing actual values. I am not familiar with the "fetch" concept since I'm coming from JDBC, however I have been spending the past few days trying to get it to work to no avail. I have looked at similar posts such as this post, and this post, and this post. These seem to handle slightly different issues. Unfortunately I want to use a prepared statement instead of an actual query.

Answer

I believe the problem is your single-quotes. Try this:

$sth = $conn->prepare("SELECT `id`, `short-des`, `full-des`, `image-urls`, `date-created` FROM projects");

Note: backticks ` are not the same as single-quotes '.