This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 1 year ago.
I am in the process of moving from hosted web sever to a VPS server I have setup with Apache, mysql, php etc. The following code works fine on my hosted server but throws an error on my VPS server
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'groups' at line 1
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$host = 'localhost';
$db = 'dbname';
$user = 'user';
$pass = 'pass';
$charset = 'utf8';
$dsn = "mysql:host=$host; dbname=$db; charset=$charset";
echo $dsn .'<br>';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$dbh = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$sql = "SELECT * FROM groups";
$sth = $dbh->prepare($sql);
$sth->execute();
If I modify the SQL query to also include the database name e.g.
SELECT * FROM dbname.groups
Then it works fine, however I am at a loss to understand why I need to specify the database name in the query for it to work when the database is already selected in the DSN and it doesn't require it on my hosted server. I'm convinced it must be to do with some setting on my new VPS but cannot figure out what it may be and have a lot of code so really don't want to have to go through and alter every single SQL query to include the database name as well.
Hosted server is PHP 7.4.24
VPS server is PHP 7.4.3
Can anyone help?
Related
I have completed all the steps to make a connection between PHP and Ms SQL but still its not working and showing an error of "Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect()". I have installed MS SQL Driver also. the extension i am using in php.ini is php_pdo_sqlsrv_53_ts_vc9.dll right now but it is not included in xampp extensions. TCP/ IP is also enabled already.
You could use PDO statement to connect
An example bellow:
# Connecting to PostGreSQL
$dbh = new PDO("msql:dbname=$dbname; host=$host", $username, $password);
# Setting an attribute on the database handle and error reporting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Prepares a statement for execution and returns a statement object
$query = 'SELECT * FROM test';
$stmt = $dbh->prepare($query);
$stmt->execute();
# Set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
# Returns an array containing all the results from the query
$allRows = $stmt->fetchAll();
I'm trying to create a database using the following code:
// Set up DB connection and creates the DB
try {
$connection = new \PDO(
'mysql:host='.Settings\Database::$host.';',
Settings\Database::$username,
Settings\Database::$password);
$connection->exec("CREATE DATABASE IF NOT EXISTS ".Settings\Database::$databaseName." CHARACTER SET utf8 COLLATION utf8_unicode_ci;");
} catch (\PDOException $exception) {
die("Could not connect to database: ".$exception->getMessage());
}
The problem is that no database is being created and I receive no error except for the fact that when I try create a table with PDO i receive this error:
READ EDIT 2
Could not connect to database: SQLSTATE[HY000] [1049] Unknown database 'dbname'
Edit:
I have no problem manually creating the DB with phpMyAdmin and similars.
Edit 2:
Mistakenly I thought that the error was given by the CREATE TABLE... statement. Instead the error is returned by the die() function in the exception handling.
Your call to exec() isn't throwing exceptions. You have to enable that for each PDO connection with an attribute like this:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If you were getting the error message from exec(), you would have seen this:
Could not connect to database: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COLLATION utf8_unicode_ci' at line 1
The syntax for CREATE DATABASE uses the keyword COLLATE, not COLLATION.
See http://dev.mysql.com/doc/refman/5.6/en/create-database.html
i'm in trouble. I'm trying to connect remote mysql server with pdo (php 5.4.12). With this code it's connect normally:
$dbh=new PDO('mysql:host=xxx.xxx.xxx.xxx;dbname=newdb', $user, $pass);
But, if i try set host with variable, like this:
$host='xxx.xxx.xxx.xxx';
$dbh=new PDO('mysql:host='.$host.';dbname=newdb', $user, $pass);
It's just thinks sometime, and tell me:
Fatal error: Uncaught exception 'PDOException' with message ' in
D:\wamp\www\test.php on line 21
21 it's line of creating new PDO object.
Ok, i'm try to catch exception (sorry, it's new for me), and now i have this:
Error!: SQLSTATE[HY000] [2002]
Can you help me, please?
Double quoting not helps
$dbh = new PDO("mysql:host=$host;dbname=newdb", $user, $pass);
Nothing changed.
var_dump('mysql:host='.$host.';dbname=newdb');
string 'mysql:host=xx.xx.xxx.xxx;dbname=newdb' (length=37)
Way with {} not helped for me.
Ok, the situation becomes clear. I'm try to connect another server on another IP, and it's normally connected. Can it be mysql server security options?
Try this way
$host = "xxx.xxx.xxx.xxx";
$dbh = new PDO("mysql:host={$host};dbname=newdb", $user, $pass);
The double quotes and the braces to include the var in the string as you can see here
http://www.php.net/manual/en/language.operators.string.php
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I've been advised to use anti-sql injection methods, as I am inserting values inside my database. I've looked around the web, and my first failed attempt is this, of which I need some help, with the PDO method. I found examples online to be waaay too empty of substance for me to understand (btw, I ran a line and it told me PDO is enabled):
Is this good in any way, shape or form?
<?php
include ('config.php');
// Host, User, Pass, DB
$con=mysqli_connect("127.0.0.1","*****","*****","*****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQLi: " . mysqli_connect_error();
}
$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';
try {
# MS SQL Server and Sybase with PDO_DBLIB
$DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
# SQLite Database
$DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
Also, I get this error upon submitting my form:
Fatal error: Call to a member function prepare() on a non-object in /home/product/*****/*****/*****/processForm-test.php on line 68
One big problem in your code is that it's using both mysqli_connect and PDO to create database connections. Don't do that; that's not supported. Use one or the other.
The lines you have that make PDO connections attempt to connect to four separate databases, SQL Server, Sybase, MySQL and SQLLite, all running on localhost. But you are keeping a handle to only the last one, since you're assigning the database connection to the same variable.
That variable $DBH is your reference to the database session (connection), if the connect succeeds. If it doesn't succeed, that gets assigned a value of false, which you can test, before you proceed.
I think all you need is a single PDO connection to MySQL, like this:
<?php
include ('config.php');
$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo "Connect failed: " . $e->getMessage();
}
I'm extrapolating here, but the most likely explanation for the error message you are getting is that you've got a line of code (not shown in your code sample) like this:
$sth = $DBH->prepare($sql);
The issue is that $DBH is not a reference to valid database connection. $DBH has a value of 'false', and that's because the attempt to connect to the database failed. And false is not an object, so there's no way it can have a method named 'prepare' associated with it.
I'm migrating my local files online and having PHP issues with my db script. Works fine locally (running PHP 5.3.8) but gives me the following errors on my server (PHP 5.3.10)
Without $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Fatal error: Call to a member function setFetchMode() on a non-object in /.../...php on line 108
With $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user '...'#'205.186.180.26' for table 'invited'
Here is my code:
class guest {
public $id;
public $guest_name;
public $url_phrase;
}
$guest = new guest;
if (isset($_GET['p'])) {
$url_phrase = urldecode($_GET['p']);
} else if (isset($_POST['p'])) {
$url_phrase = urldecode($_POST['p']);
}
if (isset($url_phrase)) {
try {
$DBH = new PDO("mysql:host=myhost.com;dbname=mydbname", "myusername", "mypassword");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$url_phrase = $DBH->quote($url_phrase);
$sql = "SELECT id, guest_name, url_phrase FROM mydbname.invited WHERE url_phrase = $url_phrase";
$stmt = $DBH->query($sql);
$stmt->setFetchMode(PDO::FETCH_INTO, new guest);
$guestNumber = $stmt->rowCount();
if($guestNumber > 0) {
etc...
}
if($guestType == "solo") {
foreach($stmt as $guest) {
$name = $guest->guest_name;
etc...
}
}
} else {
other stuff.. etc..
$DBH = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I've gotten simple select statements to work fine as this user (I don't think its permission-related), my problem seems to be with my implementation of PDO. How can I get rid of this error? Am I preparing/executing the statement in a weird way that's messing this up? Thanks for any help
I had the same problem. After I uploaded my code from local to production server, and the user had all privileges. The problem was the database name -- in my local environment it was something like dattabase1 and in production the name was different...prefix_ddatabas1. I changed the name of the database to the correct one and everything was ok.
Sounds like an access issue on the server:
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command
denied to user '...'#'205.186.180.26' for table 'invited'
Have you tested from the CLI (or some other sql client outside of PHP) to ensure your script will have access?
You will likely need to log into the db to give access to a user your script is running as or check the credentials you're using in the script are accurate for the db in the server environment.
I had same issue, code working at dev server but not at prod server, and other scripts working with same table were working. I had missed to correct database table prefixes between dev and prod environment. (the database's names were not the same) ^^
I received the same error. The dev DB name was different than the production DB name thus causing this error. I changed the name of the db in my code to the production DB name and it worked.
Thanks
You have an access violation:
Syntax error or access violation
The user/host you're using:
1142 SELECT command denied to user '...'#'205.186.180.26'
can not select from the table 'invited'