I am making a simple select from mySQL using PHP. I am doing something wrong that I can't seem to track down.
Here's my statement:
$storyTitle = $_GET['title'];
$storyDate = urldecode($_GET['date']);
$SQL = "SELECT
*
FROM
tblContent
WHERE
REPLACE(contentTitle,' ' , '-') = :storyTitle
AND
date(publishDate) = date(:storyDate)";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$q = $conn->prepare($SQL);
$q->execute(array(':storyTitle' => $storyTitle, ':storyDate' => $storyDate));
while($r = $q->fetch()){
echo $SQL;
};
This throws no errors and gives no rows.
If I replace the identifiers :storyTitle and :storyDate with a hard coded SQL statement, I get the correct results. I've stepped through and looked at the variables, and they seem right... I've already wasted so much time hunting, but I lack the expertise to pick out what I'm doing wrong.
Dump the contents of your variables. I'm suspicious of:
$storyDate = urldecode($_GET['date']);
$_GET parameters automatically are url-decoded.
you have to ask PDO to throw an error explicitly
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$q = $conn->prepare($SQL);
$q->execute(array(':storyTitle' => $storyTitle, ':storyDate' => $storyDate));
} catch (PDOException $e) {
echo $e->getMessage();
}
Related
I've just created a simple API for a CAD/MDT I'm working on, I've managed to get it to show the correct information when I do /citations/userid/1. This will then display all the correct values from the SQL database however, if I do /citations/issued_by/kevingorman1000 it will just throw an error. I can't tell what the error is as I'm using Slim php and can't seem to get the errors to display.
Any ideas why it isn't working ? I've added my code below..
$app->get('/citation/issuedby/{issued_by}', function(Request $request, Response $response){
$issued_by = $request->getAttribute('issued_by');
$sql = "SELECT * FROM ncic_citations WHERE issuedby = $issuedby";
try{
// Get DB Object
$db = new db();
// Call Connection to DB
$db = $db->connect();
$stmt = $db->query($sql);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($issby);
} catch(PDOExecption $e) {
echo '{"error"} : {"text": '.$e->getMessage().'}';
}});
Any ideas why this is the case? Does it only allow getting via number or do I need too do something else? First time using this and kinda new to PHP as well.
Thanks for any help.
Your problem is called SQL injection. You can solve it by using prepared statements. Never escape the values with quotes or anything else, as others might have suggested.
$sql = "SELECT * FROM ncic_citations WHERE issuedby = ? ";
$stmt = $db->prepare($sql);
$stmt->execute([$issuedby]);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
For a good tutorial on PDO and prepared statements I recommend: https://phpdelusions.net/pdo
It's because SQL error (missing quotes around string).
You try to send query
$sql = "SELECT * FROM ncic_citations WHERE issuedby = kevingorman1000";
Correct query has to be
$sql = "SELECT * FROM ncic_citations WHERE issuedby = 'kevingorman1000'";
I'm here trying to update my DB rows without deleting/creating new ones all the time. Currently, my DB creates new entries everytime I run this block of code. Instead of spamming my DB, I just want to change some of the values.
<?php
try {
$conn = new PDO("mysql:host=localhost;port=3306;dbname=dbname", Username, password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
}
echo "successfully updated";
?>
My assumption is my final line, the $results area. I believe it's just treating this an a new entry instead of an update. How do I go about just replacing values? some values will not change, like the username, and sometimes longitude/latitude won't need to be changed. Would that have to be a separate query, should I split this in to two scripts? Or could I just enter a blank, null value? Or would that end up overwriting the ACTUAL last coordinates, leaving me with null values? Looking for any help or guides or tutorials. Thank you all in advance.
lots of syntax error in your code. It is simple to use bindParam
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";// you forget to close statement in your code
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
read http://php.net/manual/en/pdostatement.bindparam.php
When using prepared statements, you should also make a habbit of following the set rules. Use named parameters. Try this:
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users SET lastEvent= :lastEvent, lastChat= :lastChat, lastLong= :lastLong, lastLatt= :lastLatt WHERE name= :name";
$q = $conn->prepare($sqlUPDATE);
$results = $q->execute(array(':name'=>$mUsername, ':lastEvent'=>$mEvent, ':lastChat'=>$mChat, ':lastLong'=>$mlongitude, ':lastLatt'=>$mlatitude));
}
I am trying to use PDO and prepared statements to get the primary key of a table. From other questions I saw that this is possible when executing something like this:
show index from TABLENAME where Key_name = 'PRIMARY'
The problem is that I can not use this from inside a prepared statement by using PDO under PHP. The code I use is the following:
$pdo = new PDO('mysql:host=localhost;charset=utf8;dbname=eclass', "user", "pass");
$stm = $pdo->prepare("show index from `TABLENAME` where `Key_name` = 'PRIMARY'");
$res = $stm->execute();
Now, the problem is that although the statement is created correctly, the execution fails. I am sure that this is not a permission's problem, since I run this as root with no result. When I directly run this SQL code from mysql prompt, it shows result indeed.
EDIT: It seems that after the weekend, the statement magically works. I don't know why this happened. Thank you for your help.
are you sure it fails? what is the result of this code?
$pdo = new PDO(
"mysql:dbname=" . SQL_DB . ";host=" . SQL_HOST, SQL_USER, SQL_PWD,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
try {
$stm = $pdo->prepare("show index from `TABLENAME` where `Key_name` = 'PRIMARY'");
$res = $stm->execute();
print_r($stm->fetch(PDO::FETCH_ASSOC));
} catch (Exception $e) {
print_r($e);
}
I have a MySQL database with a table (opendpu) that has multiple columns including columns titled "ECRNUM" and "PE_REQUIRED".
I'm simply trying to test this update statement by specifying some values. I get this error:
Array ( [0] => 42000 [1] => 1064 [2] => 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 'DOE WHERE ECRNUM = 81308' at
line 1 )
I cannot, for the life of me, figure out what is wrong here. Can anyone help?
<?php
require ('config.php');
$ecrno = '81308';
$pe_required = 'JOHN DOE';
while (true) {
try {
$db = new PDO($dsn, $uname, $pword);
$db->exec( "SET CHARACTER SET utf8" );
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
$db->setAttribute( PDO::ATTR_PERSISTENT, true );
break;
}
catch (Exception $e) {
$db = null;
$counter++;
if ($counter == $limit)
throw $e;
}
}
$stmt = $db->prepare("UPDATE opendpu SET PE_REQUIRED = $pe_required WHERE ECRNUM = $ecrno");
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
?>
.
+1 for using prepared statements... but (and its a big BUT):
You should never use prepared statements without bind_param as this leaves you wide open to SQL injection and negates the benefits of prepared statements.
$stmt = $db->prepare("UPDATE opendpu SET PE_REQUIRED=? WHERE ECRNUM=?");
$stmt->bind_param('si', $pe_required, $ecrno);
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
Change your syntax like this [Enclosed quotes around the variable]
$stmt = $db->prepare("UPDATE `opendpu` SET PE_REQUIRED = '$pe_required' WHERE ECRNUM = '$ecrno'");
Please check with below query
$stmt = $db->prepare("UPDATE opendpu SET PE_REQUIRED = '.$pe_required.' WHERE ECRNUM = '.$ecrno.'");
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}