What's wrong with my PDO statement? - php

// Check for existence - don't add a duplicate
$sqlQuery = $pdo->prepare('SELECT campaign_id FROM campaigns WHERE (customer_id=:customerId) AND (title=:campaignTitle) AND (description=:campaignDescription) AND (start_time=:startTimeStamp) AND (end_time=:endTimeStamp)');
$sqlQuery->bindParam(':customerId', $customerId); // , PDO::PARAM_INT
$sqlQuery->bindParam(':campaignTitle', $campaignTitle);
$sqlQuery->bindParam(':campaignDescription', $campaignDescription);
$sqlQuery->bindParam(':startTimeStamp', $campaignTitle);
$sqlQuery->bindParam(':endTimeStamp', $endTimeStamp);
$sqlResult = DatabaseCommand($sqlQuery);
results in
Fatal error: Uncaught exception 'PDOException' with message
'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 ':customerId)
AND (title=:campaignTitle) AND (description=:campaignDescription) A'
at line 1' in E:\coding\Web
Development\Xampp\htdocs\api\addCampaign.php:42 Stack trace: #0
E:\coding\Web Development\Xampp\htdocs\api\addCampaign.php(42):
PDO->query('SELECT campaign...') #1 {main} thrown in E:\coding\Web
Development\Xampp\htdocs\api\addCampaign.php on line 42
but I can't see why
[Update] for those who wanted to see the code of DatabaseCommand() this is pretty much it.
function DatabaseCommand($sqlCommand)
{
$result = $sqlCommand->execute();
return $result;
}
There is some additional code, but that just logs the command for debugging porpoises, checks for errors, logs those, catches exception & emails me.

update: seems like this isn't the solution, only improves readability
put a space between = and the parameter:
$sqlQuery = $pdo->prepare('SELECT campaign_id FROM campaigns WHERE (customer_id= :customerId) AND (title= :campaignTitle) AND (description= :campaignDescription) AND (start_time= :startTimeStamp) AND (end_time= :endTimeStamp)');

This code you posted here has nothing to do with error message you get.
You have to check addCampaign.php file, line 42 where you are using query() method instead of execute(). And of course you have to check the actual file that being executed.
I'll take the opportunity to direct all the enthusiast programmers' attention to the extreme helpfulness of reading error messages. Despite of the common belief, it is not just a reproach, reading "You've done something wrong!", leaving you to guess the reason, but precise and detailed explanation. And it only takes to read the error message to get the clue.
I'll also take the opportunity to direct all the enthusiast programmers' attention to the fact that if common practice of echoing only error message, leaving stack trace behind, were used, the information on the real cause of error were omitted.

Related

sqlserver PDO query error

I have this query to be executed:
try {
$dbh = new PDO('sqlsrv:Server=localhost;Database=database','user','pass');
} catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkQuery = "SELECT `userName` FROM `user_Status` WHERE `userName` = :userName";
$prepared = $dbh->prepare($checkQuery);
$prepared->bindValue(':userName', $_POST['username']);
$prepared->execute();
$count = $prepared->rowCount();
I am getting an error when executing this query and I have spent 3-4 hours searching for similar errors and scanning my code trying to find it but I just can't find it. I figure maybe some other sets of eyes may point it out or maybe I am just doing something completely wrong and don't realize it. Here is the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near '`'.' in C:\inetpub\wwwroot\InOutBoard\authorize.php:68 Stack trace: #0 C:\inetpub\wwwroot\InOutBoard\authorize.php(68): PDOStatement->execute() #1 {main} thrown in C:\inetpub\wwwroot\InOutBoard\authorize.php on line 68
Line 68 is the execute statement, but I don't see any problem with that and I don't see where it is getting the incorrect syntax error near ''.' as I can't find any any in my code nor anything I would see to cause an error, I don't think I'm using any reserved words either. I used to have "SELECT userName FROM Database.user_Status but I even tried removing that and nothing changed. I am sure I have the right Database, user and password as well as table. Any help?
Thank you #frz3993 and Marcus for the help. I fixed the problem by removing the backticks as I was used to using them for mySQL but forgot that I was not in need of them for mssq

MYSQLI Debug Issue

I've been absolutley hung up on this.
I'm doing a debug on my script. I'm trying to insert into my database, but everything runs fine with now errors. Nothing is inputted in the database. Okay so I forced some error reporting like so :
ini_set('display_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I got some great information & normally this part is quick, but I can't quite get what is wrong.
Fatal error: Uncaught exception 'mysqli_sql_exception' with message
'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 'explain,date_added) VALUES('Budget','','','Trading','',now()' at
line 1' in upload/inventory_list.php:74 Stack trace: #0
upload/inventory_list.php(74): mysqli_query(Object(mysqli), 'INSERT
INTO pro...') #1 {main} thrown in upload/inventory_list.php on line 74
The line in question is :
$sqls = "INSERT INTO products (product_name,price,details,category,explain,date_added)
VALUES('$product_name','$price','$details','$category','$explain',now())";
$result = mysqli_query($db_conx,$sqls);
I'm on the right line from what I'm getting from my typical debug, but I can't seem to trace it. Any help is greatly appreciated.
Yes you have an obvious error in the query
$sqls = "INSERT INTO products (product_name,price,details,category,explain,date_added)
VALUES('$product_name','$price','$details','$category','$explain',now())";
should be
$sqls = "INSERT INTO products (product_name,price,details,category,`explain`,date_added)
VALUES('$product_name','$price','$details','$category','$explain',now())";
explain is a reserved key word so use backticks for that

Adding column to table returns error saying error in SQL syntax

When I run this code:
$addUniverseColumn = $db->prepare("ALTER TABLE spaceships ADD :universe int");
$addUniverseColumn->bindParam(":universe", $name);
$addUniverseColumn->execute();
I get the following error:
Fatal error: Uncaught exception 'PDOException' with message '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 ''asfa' int' at line 1' in D:\XAMPP\htdocs\php\locationconfig.php:63 Stack trace: #0 D:\XAMPP\htdocs\php\locationconfig.php(63): PDOStatement->execute() #1 {main} thrown in D:\XAMPP\htdocs\php\locationconfig.php on line 63
Note: $addUniverseColumn->execute(); is the line 63.
I have little to no idea as to what the problem is. I've searched for an answer to the problem but I can't find anything. Any help would be appreciated. :)
Placeholders can only work for VALUES, never field/table names. You cannot use a placeholder for the field name in an ALTER query. You'll have to use good old string interpolation for it:
$db->prepare("ALTER TABLE spaceships ADD $name int");

using LEAST in SQL query when using PHP PDO Prepared statements

i am trying to use this PHP PDO prepared statement to run an SQL Query:
$stmt = $pdo_conn->prepare("SELECT *, LEAST(:col_list) as num FROM callplandata WHERE number LIKE :number HAVING num != 0 ");
$stmt->execute(array(':col_list' => implode(',',$column_list), ':number' => '%'.$_POST["prefix"].'%'));
but its showing this error message:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1582 Incorrect parameter count in the call to native function 'LEAST'' in /home/integra/public_html/included_pages/call_tarrif_search.php:62 Stack trace: #0 /home/integra/public_html/included_pages/call_tarrif_search.php(62): PDOStatement->execute(Array) #1 /home/integra/public_html/index.php(119): include('/home/integra/p...') #2 {main} thrown in /home/integra/public_html/included_pages/call_tarrif_search.php on line 62
what am i doing wrong?
LEAST accepts 2 or more values and returns the least one.
You're passing a single value, that is the roots of the error.
PS: and as soon as you haven't explained the original issue - there is nothing to add here. Please don't ask "how to fix it" because we have no idea what you're trying to achieve.

PDO Find a needle in a haystack SQL statement

I am using PDO, and am thrown an error when using the following code:
$stmt = $pdo->prepare("SELECT username FROM users WHERE
WHERE INSTR(`games`, '{$gameid}') > 0
");
$gameid = $gamedata['id'];
$stmt->execute(array(
':gameid'=>$gameid
));
$players = $stmt->fetch(PDO::FETCH_ASSOC);
Through looking at past answers this is supposed to work, however I am met with the following error:
Fatal error: Uncaught exception 'PDOException' with message '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 'WHERE
INSTR(`games`, 'crysis') > 0' at line 2' in C:\xampp\htdocs\gs\gamepage.php:19 Stack
trace: #0 C:\xampp\htdocs\gs\gamepage.php(19): PDOStatement->execute(Array) #1 {main}
thrown in C:\xampp\htdocs\gs\gamepage.php on line 19
It also appears it's grabbing 'games' as a literal and not the column
What am I doing wrong?
You have a double WHERE:
SELECT username FROM users WHERE
WHERE
You're also doing some funny things with $gameid, namely setting the variable after substitution, and binding an unused :gameid parameter. You also have a SQL injection vulnerability and should really use a parameter to pass $gameid instead of creating dynamic SQL.
You have the word games encased in "back quotes" and not "single quotes" like the {$gameid} variable is using. They are probably making the db engine assume it is a column name instead of text.
$stmt = $pdo->prepare('SELECT `username` FROM `users`
WHERE INSTR(`games`, :gameid) > 0;');
And you should use $stmt->bindValue() or $stmt->bindParameter() before executing the query.
This won't work if gameid is an ... INTEGER ! ? ! ?

Categories