Search code examples
phpmysqlselectlimit

Error undeclared variable when select using limit


I have an error in my script select MySQL with limit. it said

Gagal ambil data:Undeclared variable: $st

this is my script :

include'../konekdb.php';
if(empty($_GET[start]))
{
$st="0";
}
else 
{
	$st=$_GET[start];
}
$query = 'SELECT * FROM pelanggan LIMIT $st,5';
$ambildata = mysql_query($query);
if(!$ambildata)
{
	die('Gagal ambil data:'.mysql_error());
}
include'tabel_pelanggan.php';
	
mysql_free_result($ambildata);
mysql_close($koneksi);
				
$query2 = mysql_query("SELECT * FROM pelanggan");
$num = mysql_num_rows($query2);
$hal = ceil($num/5);
echo "Halaman :";
for($i=1;$i<=$hal;$i++){
$page=$i-1;
echo "[][<a href=$_SERVER[PHP_SELF]?start=$page>$i</a>][]";
}

can you help me? thanks before :)


Solution

  • You have an error with you $_GET, you're missing the quotes around the key name.

    Your $_GET,

    $st=$_GET[start];
    

    What it should be,

    $st = $_GET['start'];
    

    Edit 1

    You shouldn't be using MySQL now as it is deprecated. Either start using MySQLi or PDO, you should also look in to prepared statements.

    Edit 2

    Also don't forget to change your if statement too.

    From

    if(empty($_GET[start]))
    

    To,

    if(empty($_GET['start']))
    

    Edit 3

    Your query needs to use double quotes or if you want to use single quotes you need to close the single quotes then add the variable on.

    From,

    $query = 'SELECT * FROM pelanggan LIMIT $st,5';
    

    To,

    $query = 'SELECT * FROM pelanggan LIMIT ' . $st . ',5';
    

    Or,

    $query = "SELECT * FROM pelanggan LIMIT {$st},5";