You have an error in your SQL syntax

I dont know how to fix this type of error I am facing this syntax error first time. any clue what is going wrong?I am creating a download counter with unique Ip address.

error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘223.185.43.151’)’ at line 1

link:

<a href="include/count.php?url=<?php echo $row['c_ext'];?>&cource_id=<?php echo $_GET['cource_id']; ?>" >

count.php

<?php

include "connect.php"; /* Database connection */
$c_id= $_GET['cource_id'];
$date=date("Y-m-d"); /* returns current date in yyy-mm-dd */
$userip=$_SERVER['REMOTE_ADDR']; /* store ip*/
$webpage=htmlspecialchars($_SERVER["REQUEST_URI"]);
$lastword = substr($webpage, strrpos($webpage, '/') + 1);

$query="select * from `unique_download` where `webpage`='$lastword'";
$result=mysqli_query($db,$query);
if($result->num_rows==0) /* block will execute when there is no record of current date in the database table */
{
	$insertquery="insert into `unique_download`(`c_id`,`date`,`webpage`,`ip`) values ('$c_id','$date','$lastword,'$userip')";
	mysqli_query($db,$insertquery) or die(mysqli_error($db));
	

}
else
{
	$row=mysqli_fetch_array($result); /* Extracts result row From result object */
	if(!preg_match('/'.$userip.'/i',$row['ip'])) /* Execute when current ip is not in database*/
	{
		$newip="$row[ip]$userip"; /* Combines previous and current user ip with separator */
		$updatequery="update `unique_download` set `ip`='$newip', `downloads`=`downloads`+1 where `webpage`='$lastword'";
		mysqli_query($db,$updatequery) or die(mysqli_error($db));
	}
}

$url= $_GET['url'];


 header('location:downloader.php?url='.$url);


?>

downloader.php

<?php
ob_start();

if(isset($_GET['url']))
{
    $var_1 = $_GET['url'];

    $dir = "../img/uploads/"; 
    $file = $dir . $var_1;

    if (file_exists($file))
    {
      $strFile = file_get_contents($file);			

	  header("Content-type: application/force-download");
	  header('Content-Disposition: attachment; filename="'.$var_1.'"');	
	  
	  header('Content-Length: ' . filesize($file));	
	  echo $strFile;
	  while (ob_get_level()) {
		ob_end_clean();
	  }
	  readfile($file);	 
		exit;
    }
} else
{
    
    echo "content dosn't exist";
}

?>

any help is appreciated.Thankyou

A couple things. First off you need to use prepared statements. That would fix the error you’re getting. Second you only need one query. Set a unique constraint to the column and then use INSERT IGNORE

2 Likes

sir kindly guide me through the code plz.

I’m guessing that the database connection failed.

Try adding these line to count.php:

<?php
  // LINES TO BE ADDED 
	ini_set('html_errors', 'true');
	ini_set('display_errors', 'true');
	ini_set('display_startup_errors', 'true');
	error_reporting(-1);

include "connect.php"; /* Database connection */

Edit:
Also learn how to echo $variables and stop the script before the actual error occurs. once satisfied the $variable is correct then move the line furher down to the next problem.

I know it is tedious but that is programming unfortunately :frowning:

<?php 
...
... 
...
$query = "select * from `unique_download` where `webpage`='$lastword'";
echo '<br>$query ==> ' .$query .'<br>'; die;

$result=mysqli_query($db,$query);
if($result->num_rows==0) /* block will execute when there is no record of current date in the database table */
{
	$insertquery="insert into `unique_download`(`c_id`,`date`,`webpage`,`ip`) values ('$c_id','$date','$lastword,'$userip')";
	mysqli_query($db,$insertquery) or die(mysqli_error($db));
	

I am using 000webhost.com
https://status.000webhost.com/

Freaking 000webhost DB is down for 5h, could that be a result for this?
My website is also down today for some DB error.

I try and paste the above line but nothing happens! http://bvocation.ml/include/count.php?url=log.png&cource_id=2

Try remming out sections of script to eliminate the errors because it is best to start with something that works then add script until an error occurrs:

Edit:
Notice how I have changed the /*block comments*/ to single line //comments

<?php
// LINES TO BE ADDED 
	ini_set('html_errors', 'true');
	ini_set('display_errors', 'true');
	ini_set('display_startup_errors', 'true');
	error_reporting(-1);

echo __LINE__; die;

/*  // THIS LINE TO BE MOVED DOWN ONCE __LINE__ IS SHOWING

// Database connection 
include "connect.php"; 
$c_id= $_GET['cource_id'];
 // returns current date in yyy-mm-dd 
$date=date("Y-m-d"); 
// store ip
$userip=$_SERVER['REMOTE_ADDR']; 
$webpage=htmlspecialchars($_SERVER["REQUEST_URI"]);
$lastword = substr($webpage, strrpos($webpage, '/') + 1);

$query="select * from `unique_download` where `webpage`='$lastword'";
$result=mysqli_query($db,$query);
// block will execute when there is no record of current date in the database table
if($result->num_rows==0)  
{
  $insertquery="INSERT INTO `unique_download`
    (
      `c_id`,`date`,`webpage`,`ip`
    ) 
    VALUES
     (
      '$c_id','$date','$lastword,'$userip'
     )";
  mysqli_query($db,$insertquery) or die(mysqli_error($db));

}else{
  // Extracts result row From result object 
  $row=mysqli_fetch_array($result); 
  // Execute when current ip is not in database
  if(!preg_match('/'.$userip.'/i',$row['ip'])) 
  {
    // Combines previous and current user ip with separator 
    $newip="$row[ip]$userip"; 
    $updatequery="update `unique_download` set `ip`='$newip', `downloads`=`downloads`+1 where `webpage`='$lastword'";
    mysqli_query($db,$updatequery) or die(mysqli_error($db));
  } // pregmatch
}
$url= $_GET['url'];
 header('location:downloader.php?url='.$url);

*/ // CLOSING REM STATEMENT TO BE REMOVED ONCE ALL ERRORS HAVE BEEN FIXED

// ? > NOT REQUIRED and possible to cause errors

I used the above code now its just shows up 8 whats does it mean?
http://bvocation.ml/include/count.php?url=log.png&cource_id=2

Try this because I think the query is mistaking the single back–ticks as table field names:

  $sql = 'INSERT INTO `unique_download` 
    (
      `c_id`,  `date`,  `webpage`,  `ip`
    ) 
    VALUES
     (
       "$c_id",  "$date",  "$lastword",  "$userip"
     )';
  echo $sql; die;

  $insertquery = $sql;

  mysqli_query($db,$insertquery) or die(mysqli_error($db));

its showsup the query now http://bvocation.ml/include/count.php?url=log.png&cource_id=2
I replace my sql query with your and now its print the sql direct

The 8 is the script/file line number which is useful with lengthy scripts.

Also can use __FILE__ and quite a few other PHP Constants.

1 Like

ohky, now whats next?

Did you spot the difference?

BEWARE:
There is an enormous difference between single-quotes, double-quotes and back-ticks. Please learn how to use then in the correct place.

I replace double with single quotation ‘$c_id’,‘$date’,‘$lastword,’$userip’ but its result:

Parse error: syntax error, unexpected ‘$c_id’ (T_VARIABLE) in /storage/ssd3/574/6271574/public_html/include/count.php on line 26

$c_id is define above the code why its showsup the error?

1 Like

date isn’t going to work without giving it special treatment because it’s a “reserved keyword”
https://dev.mysql.com/doc/refman/5.5/en/keywords.html

Reserved words are permitted as identifiers if you quote them as described in Section 9.2, “Schema Object Names”:

1 Like

The expanded line shows the $sql statement starts with a single quote and continues until the next single-quote.

Edit:
I’m off out for a late lunch…

1 Like

ohky I got it. now still this error is back
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘106.204.62.208’ )’ at line 7

No problem sir take your time

this is the cause of error: replacing single quotation with " ‘.$variable.’ "

thankyou very much John_Betong for your help and give me your important time to correct my misstakes.

You could just do this, which is more readable than your current statement:

$sql = "INSERT INTO `unique_download`
    (
      `c_id`,  `date`,  `webpage`,  `ip`
    )
    VALUES
     (
       $c_id, $date, $lastword, $userip
     )";

And you should use prepared statements to prevent sql injection, like @benanamen mentioned earlier.

3 Likes

thankyou very much TeNDoLLA.I already try:

VALUES
     (
       $c_id, $date, $lastword, $userip
     )";

but its seems not work! then I used this one:

VALUES
     (
       "'.$c_id.'", "'.$date.'", "'.$lastword.'", "'.$userip.'"
     )';

and its seem work great.thankyou for the help!