Why do I get "Unexpected T_AS" in PHP PDO request? - php

I receive the following error...
Parse error: syntax error, unexpected T_AS in ....\index.php on line 98
for the following script...
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'pw');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT * FROM tablename");
$stmt->execute();
while($db->fetch(PDO_FETCH_ASSOC) as $row) {
$id= $row['id'];
$name= $row['name'];
}
$db->commit();
}
catch (PDOException $e)
{
$db->rollback();
echo "There was a system error.<br>".$e->getMessage();
}
?>
Any idea what is throwing the error? I have checked for missing semicolons, commas, and the works but got nothing!

Parse error: syntax error, unexpected T_AS in ....\index.php on line 98
T_AS is the token for as in the PHP interpreter. It was unexpected when trying to parse your code's syntax.
as is only valid in a foreach loop, and you are using a while.
Change your while loop to a foreach loop.
Update
Fatal error: Call to undefined method PDO::fetch() in index.php on line 113
This is a run time error - the PDO object has no method called fetch(). Are you calling fetch() on the right object?
Check out the documentation.
As Wrikken states in the comments, it will be a method of your $stmt object.

Because you are using the 'as' keyword in a 'while' loop, which is not valid. Change the 'while' to 'foreach' and you are good to go.

Related

Fatal error: Uncaught Error: Call to a member function fetch() on bool

I try to access to database from PostgreSQL by using PHP.
I run this code, but I got an error:
VM6722:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success ((index):58)
at c (jquery-3.4.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
at l (jquery-3.4.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)
I'm trying to figure out but I'm very new to php. SO I would appreciate any inputs to fix this issue.
<?php
$db = new PDO('pgsql:host=localhost;dbname=webmap103;', 'postgres', 'postgres');
$sql = $db->query("SELECT id, name, image, web, category,ST_AsGeoJSON(geom, 5) as geom FROM cdmx_attractions ORDER BY name");
$features = [];
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$feature = ['type'=>'Feature'];
$feature['geometry'] = json_decode($row['geom']);
unset($row['geom']);
$feature['properties'] = $row;
array_push($features, $feature);
}
$featureCollection = ['type'=>'FeatureCollection', 'features'=>$features];
echo json_encode($featureCollection);
?>
I expected to show the data on my web application.
I'm using html and ajax to call php to get an access to my database on postgresql.
If your sql statement fails $db->query(...) returns false. Check to see if your sql statement is valid and executes properly. If it is false you will get the error "Fatal error: Uncaught Error: Call to a member function fetch() on bool"
As Engin said, $db->query() return false when it fails. See https://www.php.net/manual/en/pdo.query.php
PDO::query() returns a PDOStatement object, or FALSE on failure.
Don't call your PHP using Ajax, at least to debug. It will be way easier to see the error. Just call your PHP route directly in a browser. json is a mess to debug in a browser console.
Try to catch errors and display it using PHP :
<?php
try{
$db = new PDO('pgsql:host=localhost;dbname=webmap103;', 'postgres', 'postgres');
$sql = $db->query("SELECT id, name, image, web, category,ST_AsGeoJSON(geom, 5) as geom FROM cdmx_attractions ORDER BY name");
$features=[];
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$feature=['type'=>'Feature'];
$feature['geometry']=json_decode($row['geom']);
unset($row['geom']);
$feature['properties']=$row;
array_push($features, $feature);
}
$featureCollection=['type'=>'FeatureCollection', 'features'=>$features];
echo json_encode($featureCollection);
} catch (Exception $e) {
var_dump($e->getMessage());
var_dump($e->getCode());
}
}
?>
Check your PHP logs (I don't know what is your OS or version of PHP but here is a quick exemple on debian, using PHP7.3-FPM :
tail -f /var/log/php7.3-fpm.log
Call your page and watch your shell.

Error: SQLSTATE[HY000]: General error [duplicate]

I am getting an error when updating a database using PDO.
I am new to PDO so maybe the problem is a small one and I just don't understand.
Funny thing about the error, the command works fine and the database does actually get updated.
But it still returns an error back at me.
Code:
try {
$stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'");
$stmt->execute(array(
'new_content' => $new_content
));
$result = $stmt->fetchAll();
echo "Database updated!";
}
catch(PDOException $e) {
echo 'ERROR UPDATING CONTENT: ' . $e->getMessage();
}
Error:
ERROR UPDATING CONTENT: SQLSTATE[HY000]: General error
I literally have no idea where the problem could be because its very vaque and I haven't been able to find anyone with the same problem.
You do not use fetchAll(),as in
$result = $stmt->fetchAll();
with update or insert queries. Removing this statement should rectify the problem.
Just to note, another possible reason for this error is if you make a second database call with the variable $stmt inside of an existing parent $stmt loop.
$stmt = $conn->query($sql);
while ($row = $stmt->fetch()) { //second use of $stmt here inside loop

Wierd MySQL/PHP error

I'm trying to get a list from my MySQL database, which normally works fine. But today I'm getting this error Fatal error: Call to a member function setFetchMode() on a non-object in "Way too long path to file here".
This is my PHP code:
$conn = new PDO('mysql:host=localhost;port=3306;name=erty', 'erty', 'Ops, that my password ...');
$result = $conn->query("SELECT name FROM mod_devs");
$result->setFetchMode();
foreach ($result as $row) {
echo '<tr><td>'.$row['name'].'</td></tr>';
}
Now, you probably understand my goal :)
Generally Call to a member function setFetchMode() on a non-object means that $result is not available. Probably because of MySQL error - either in connection or query. Check if($conn) or if($result).
You still need to fetch the result...
So instead of foreach....do while...
while ($row = $result->fetch()) {
//your code here
}
you maybe need prepare not query
$result = $conn->prepare("SELECT name FROM mod_devs");
or this
$result->setFetchMode(PDO::FETCH_OBJ);
I just found the error. In the connection I wrote name=erty not dbname=erty!
Sorry for taking up your time :(

Parse Error with MongoCursor::doQuery in php function?

When i try to execute this one function, it returns an error saying "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM on line 103".
In line 103, it looks like (This is the beginning part of the code)
function get_list($option)
{
//$db = new db();
//$db->getConnection();
$rs = $this->db->MongoCursor::doQuery($this->sql, $this->sql_params); //this is the line 103
$this->resultList = $rs;
What am I doing wrong?
You can not mix static and instance syntax. It would either be:
$rs = $this->db->MongoCursor->doQuery($this->sql, $this->sql_params);
or
$rs = MongoCursor::doQuery($this->sql, $this->sql_params);
I don't know what framework if any that you are using to tell you exactly what it should be but what I showed you will fix the syntax error.
$this->db looks like it might be Codeigniter? But MongoCursor::doQuery() is vanilla PHP: http://php.net/manual/en/mongocursor.doquery.php

PHP PDO MySQL query prints blank

Going through a PHP MySQL tutorial and switching the PHP out for PDO; at any rate, my query is coming up blank.
$get_cat = $that->dbh->query("SELECT `cat_name`, `cat_desc` FROM `categories`");
if(isset($get_cat))
{
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
{
printf("
<tr>
<td>".$row['cat_name']." : ".$row['cat_desc']."</td>
</tr>
");
}
}
else
{
echo '<tr><td>return is false</td></tr>';
}
$That refers to:
include('db.php');
$that = new lib();
OLD:
So, why is my query blank? Before putting the die in it would return Boolean and give in an error in the loop with the die in it just comes up blank. The categories table has data in it and the page is refreshed on submission for new entries.
NEW:
Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\forum\create_category.php on line 36
Line 36 is the while loop line.
mysql_fetch_array is not PDO. You would need something like:
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
To get your rows.
Nor can you use mysql_error() to get the error. You could use for example $that->dbh->errorInfo() but you should look into exceptions for a more robust way to catch all errors.
Edit: You should check what the error is. Using isset is pointless as you have just assigned a value to it, so it will always be set.
You need to tell PDO to throw errors.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res = $that->dbh->query("SELECT cat_name, cat_desc FROM categories");
while($row = $res->fetch())
{
echo "<tr><td>$row[cat_name] : $row[cat_desc]</td></tr>\n";
}
run your code, read the error message and take appropriate action
Don't forget to add the first line into your db.php file, to make the setting permanent
Your query is incorrect -- is this what you're trying to do?
SELECT `categories`.`cat_name`, `categories`.`cat_desc` FROM `categories`
Hard to know without seeing you table structure.

Categories