Jessica Habze
Jessica Habze

Reputation: 29

Difficult SQL query syntax

Hello guys here are my MySQL query which one getting data...

$videofetch = $conn->prepare("select * from user_followers as uf join videos as v on uf.followed_id = v.publisher_id where uf.follower_id = ? order by video_id desc limit 5");
$videofetch->execute(array(@$_SESSION ["userid"]));
$vid = $videofetch->fetchALL(PDO::FETCH_ASSOC); 

This code is working perfect, But when i am trying to get more data with AJAX i can't write the correct sql query syntax.

<?php
session_start();
if(isset($_POST["id"]) && !empty($_POST["id"])) {
  include('connectdb.php');
  $lastID = $_POST['id'];
  $videofetch = $conn->prepare("select * from  user_followers as uf join videos  as v  on uf.followed_id = v.publisher_id where uf.follower_id = ? order by video_id  desc limit 5");
  $videofetch->execute(array($_SESSION["userid"]));
  $vid = $videofetch->fetchALL(PDO::FETCH_ASSOC);
  ...

I want to add WHERE video_id < ".$lastID." .. I tryed couple of combinations but everytime displaying syntax error.

Notes:

1- I am getting data from AJAX to $lastID;

2- $_SESSION ["userid"] is active, dont worry about this

3-SQL error is:

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 'as v on uf.followed_id = v.publisher_id where uf.follower_id = '1' order by vid' at line 1 in C:\wamp64\www\hola.com\functions\getdatafoll.php on line 9

Upvotes: 0

Views: 82

Answers (1)

Djaevel
Djaevel

Reputation: 192

Try to upercase your mysql keywords. its much better to read.

And you already have a WHERE, so you just need to combine it with an AND.

SELECT  *
    FROM  user_followers AS uf
    JOIN  videos AS v  ON uf.followed_id = v.publisher_id
    WHERE  uf.follower_id = ?
      AND  video_id < ".$lastID."
    ORDER BY  video_id DESC
    LIMIT  5 

But change the ' ".$lastID." with a prepared statment.

Upvotes: 1

Related Questions