Query Error: where is the error? - php

I am getting the following error:
[07-Mar-2011 04:52:31] exception 'Exception' in /home1/mexautos/public_html/kiubbo/data/model.php:89
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(276): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('')
#5 {main}
This is the line: $lastid = parent::execSql2($query);
Here is the code, if someone can help me to find where the error is:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', '$this->points' )";
}
else if($this->id != 0)
{
$query = "update articles set modified = CURRENT_TIMESTAMP, username = '$this->username', url = '$this->url', title = '$this->title', description = '$this->description', points = '$this->points', ranking = '$this->ranking' where id = '$this->id' ";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
}

You have to enclose the variables in {}tags; like so
$query .= " values ('{$this->getModified()}', '{$this->username}', '{$this->url}', '{$this->title}', '{$this->description}', '{$this->points}' )";
The curly brackets let PHP know not to treat the text as a literal. Please note that this will only work in a double-quoted string. (editted the code; I forgot the single quotes around every value)
It might be helpful to echo the string, so that you can check what's going to be executed.

$query .= " values ('".$this->getModified()."', '".$this->username."', '".$this->url."', '".$this->title."', '".$this->description."', '".$this->points."' )";

Related

How do i troubleshoot this MySQL error?

I'm making a simple website for a class, and I am trying to save information to my database. The error is not very specific and I do not know which part of my code I need to fix.
Error message:
check the manual that corresponds to your MariaDB server version for
the right syntax to use near ')' at line 2
My PHP code:
<?php
include 'mysqli.php' ;
$result = $con->query("select * from setList s
left join songTable t on s.SetList_ID = t.Song_ID
left join bands b on s.SetList_ID = b.Band_ID");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$setList = $_POST['setlist'];
$venue = $_POST['venue'];
$date = $_POST['dateOfShow'];
$band= $_POST['band'];
$set = $result->fetch_object();
//error handling and form
try {
if (empty($setList) || empty($venue) || empty($date) || empty($band)) {
throw new Exception(
"All Fields Required");
}
if (isset($set)) {
$id = $set->SetList_ID;
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
}
else{
$q = "insert setList (SetList_Name, Venue, Show_Date, Band_Name)
values ('$setList', '$venue', $date, '$band')";
}
$result = $con->query($q);
if (!$result) {
throw new Exception($con->error);
}
header('Location:my_set-lists.php');
} catch(Exception $e) {
echo '<p class ="error">Error: ' .
$e->getMessage() . '</p>';
}
}
?>
The error message tells you exactly where the problem is; you have an extra ). Replace
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
// extra ) is here ---------------------------------------------^
With
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band'";
Note: your next query (starting insert setList) is also going to fail; it should be INSERT INTO setList.... A decent IDE (like PHPStorm) would catch these errors for you.
Also, you are wide open to SQL injection. You really need to be using prepared statements.

null values in mysqli parameters

my mysql table accepts NULL values on many fields, I'm updating records and my desktop app is creating a http string as follows and sending to a php script.
www.webpage/script.php?firstval=48.345345&secondval=234&thirdval=&fourthval=simon
on the db thirdval is already NULL
but the parameters in the http string may or may not hold values
do I need to :
A)pass the parameter in the http string as
b)pass the parameter in the httpstring as
c)cater for the null value in the php script(
d)not include the parameter in the http string at all
or something else
my phpscript is like so :
?php
DEFINE ('DBUSER', 'generic01');
DEFINE ('DBPW', 'genpass');
DEFINE ('DBHOST', 'mysql4.xxxxxxxxx.com');
DEFINE ('DBNAME', '_Places');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die(" Database selection bit failed: " . mysqli_error($dbc));
exit();
}
$lat = mysqli_real_escape_string($dbc, $_GET['lat']);
$lng = mysqli_real_escape_string($dbc,$_GET['lng']);
$prox = mysqli_real_escape_string($dbc,$_GET['prox']);
$description = mysqli_real_escape_string($dbc,$_GET['description']);
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$direction = mysqli_real_escape_string($dbc,$_GET['direction']);
$avoiddays = mysqli_real_escape_string($dbc,$_GET['avoiddays']);
$validfrom = mysqli_real_escape_string($dbc,$_GET['validfrom']);
$validto = mysqli_real_escape_string($dbc,$_GET['validto']);
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
$expiry = mysqli_real_escape_string($dbc,$_GET['expiry']);
$query = "UPDATE places SET rt_lat = '$lat',rt_lng= '$lng',rt_prox = '$prox', rt_description = '$description', rt_direction = '$direction',rt_avoiddays = '$avoiddays',rt_validto = '$validto',rt_validfrom = '$validfrom',rt_gefid = '$gefid',rt_expiry='$expiry' WHERE rt_id = '$id'";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
All help appreciated,
You do not need to include it in the http request, but you have to catch that, otherwise you get an E_NOTICE error.
For all fields that can be null:
if (isset($_GET['gefid'])) {
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
} else {
$gefid = null;
}
PHP has no knowledge of SQL nulls. If you want a blank/not-set $_GET value to become a null in the DB, then you have to take special steps:
if(isset($_GET['lat']) || ($_GET['lat'] == '')) {
$lat = 'NULL'; // a plain PHP string with the word "null" in it
} else {
$lat = "'" . mysqli_real_escape_string($dbc, $_GET['lat']) . "'"; // note the extra quotes
}
$sql = "INSERT ... VALUES ($lat, ....)"
If you do it any other way, e.g (just as an example, yes it's sql-injection vulnerable):
$sql = "INSERT ... VALUES ('$_GET[lat]', ...)";
Then for an empty $_GET['lat'] your query would actually be
INSERT ... VALUES ('', ...)
and you'd be inserting an empty string, NOT an sql null.

Throw an exception with the SQL error message

I am getting an error in this code:
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', '$this->points' )";
}
else if($this->id != 0)
{
$query = "update articles set modified = CURRENT_TIMESTAMP, username = '$this->username', url = '$this->url', title = '$this->title', description = '$this->description', points = '$this->points', ranking = '$this->ranking' where id = '$this->id' ";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
What do I have to add so I get some meaningful SQL error message?
(It seems for some queries its not getting the user name)
Edit: I get this error log:
[18-Mar-2011 05:19:13] exception 'Exception' in /home1/mexautos/public_html/kiubbo/data/model.php:90
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(276): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('426')
#5 {main}
Thank you,
Regards,
Carlos
The best way to handle this is to use a custom exception that would be thrown by your Database Handler.
class DatabaseErrorException{
public function __construct( $errorMesssage, $query ){
throw new Exception( $errorMessage . " for query: " . $query );
}
}
and so you can either detect the error in your database library and throw from there, or in your try statement you can have:
if( $db->someError )
throw new DatabaseErrorException( $db->someError, $query );
and your catch statement would turn into
catch( DatabaseErrorException $e ){
error_log( $e->getMessage( ) );
//Or whatever handling you wish to do with it.
}
error_log('Failed to set record in articles table: '.
$e->getMessage().
"\n".$query
);

Query Error on db connection

Looking on my error log I get the following error a lot:
[01-Mar-2011 04:31:27] exception 'Exception' with message 'Query failed' in /home1/mexautos/public_html/kiubbo/data/model.php:89
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(275): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('')
#5 {main}
If I go to the model.php file I see this:
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Does Anybody see an error, or i should look somewhere else?
Thank you and Regards,
Carlos
Edit:
This is the query: $lastid = parent::execSql2($query);
And this is the context:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
}
Regards,
Carlos
As heximal said, it's probably an error in your SQL query. Copy and paste the full SQL being queried into PhpMyAdmin or a similar tool and see what errors (if any) come up. Often, the problem is simply a mistyped table or a missing value.
Of course you can also post the query here if you want SO help with it! :D
The error is propably in sql-query. Append to log query text and analyze it.

Is this the right place to call the RSS building function?

Is this the right place to call the function that builds the RSS? its for a reddit type of site.
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
createRSS(); //**** rss function****
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
throw $e;
}
}
Thanks a lot
Probably not. There may be times when you want to save an article object without updating your RSS feed -- e.g. you might import an archive of articles at some point. As such, whatever is responsible for calling save() should call createRSS() itself immediately afterward.
e.g.
function createArticle($title, ...) {
$article->setTitle($title);
...
$article->save();
createRSS();
}

Categories