Reputation: 11
Alright, so I have a simple database with one table, and I have a function which is supposed to get all the rows for that one table:
function get_days() {
global $db;
$query = 'SELECT * FROM days'
. 'ORDER BY idDays';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
I've checked everything else, everything else functions just fine, including the part of my site where I input data into the table, that insert statement works just fine, so I've narrowed it down to this one select statement.
Upvotes: 1
Views: 496
Reputation: 338
This is simple way to select you can use a function for it.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM days ORDER BY idDays";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//do anything
}
} else {
echo "0 results";
}
Upvotes: 1
Reputation: 8773
The problem is the string concatenation of your query:
$query = 'SELECT * FROM days' . 'ORDER BY idDays';
This results in: SELECT * FROM daysORDER BY idDays
Include a space character instead:
$query = 'SELECT * FROM days' . ' ORDER BY idDays';
You can avoid problems like this with proper error handling:
try{
$statement->execute();
}
catch(PDOException $e){
exit($e->getMessage());
}
You might also want to remove the spaces in:
$db ->prepare($query);
$statement ->execute();
So they become:
$db->prepare($query);
$statement->execute();
Upvotes: 1
Reputation: 689
The problem is in you SQL syntax. You should do this:
function get_days() {
global $db;
$query = 'SELECT * FROM days '
. 'ORDER BY id';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
Upvotes: 1