I dont understand what im doing wrong, im getting this message:
Notice: Undefined index: page in /Users/prinect/htdocs/sistema-noticias/classes/Article.php on line 221
My code:
public static function getList( $numRows=30, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$offset = ($_GET['page'] - 1) * $numRows;
$rowCount = 20;
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY {$order} LIMIT :offset, :rowCount";
$st = $conn->prepare( $sql );
$st->bindValue( ":rowCount", $rowCount, PDO::PARAM_INT );
$st->bindValue( ":offset", $offset, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
Undefined index means in your case that you are trying to access to an element of an array that does not exist.
It is most likely your $_GET['page']. Do you check if this exists? You should.
For example:
$page = (isset($_GET['page']) ? $_GET['page'] : 1; // 1 is the default page number
you need to check the page if it don't exist because when the page is not in the query param it will be considered as undefined
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $numRows;
$rowCount = 20;
Related
This question already has answers here:
php $_GET and undefined index
(12 answers)
Closed 1 year ago.
someone can help me. im geting error with code
Notice: Undefined index: user_id in D:\xampp\htdocs\public\s_game\login\gamelogin.php on line 14
Notice: Undefined index: user_pass in D:\xampp\htdocs\public\s_game\login\gamelogin.php on line 15
and here code
<?php
require '../config.php';
function antiinjection($str) {
$banwords = array ("'", ",", ";", "--");
if ( preg_match( "/[a-zA-Z0-9]+/", $str ) ) {
$str = str_replace ( $banwords, '', $str );
} else {
$str = NULL;
}
return $str;
}
$user_id = antiinjection($_GET['user_id']);
$user_pass = antiinjection($_GET['user_pass']);
$connInfo = array(
'Database' => $db,
'UID' => $user,
'PWD' => $pass
);
$conn = sqlsrv_connect($host, $connInfo);
$sql = "SELECT * FROM Account WITH (NOLOCK) WHERE UserId = ? AND Activated = 1";
$res = sqlsrv_query($conn, $sql, array($user_id), array( "Scrollable" => 'static' ));
if (sqlsrv_num_rows($res)>0)
{
$sql = "SELECT isUserCreated,Password,ID,UserKey,Email,BlockedEndDate FROM Account WITH (NOLOCK) WHERE UserId = ?";
$r2 = sqlsrv_query($conn, $sql, array($user_id), array( "Scrollable" => 'static' ));
sqlsrv_fetch( $r2 );
$userPass = sqlsrv_get_field($r2, 1);
$ID = sqlsrv_get_field($r2,2);
$userKey = sqlsrv_get_field($r2,3);
$email = sqlsrv_get_field($r2,4);
$sql = "SELECT DATEDIFF(day, getdate(), BlockedEndDate) FROM Account WITH (NOLOCK) WHERE UserId = ?";
$r3 = sqlsrv_query($conn, $sql, array($user_id), array( "Scrollable" => 'static' ));
sqlsrv_fetch( $r3 );
if (sqlsrv_get_field($r3,0) >= 0)
{
$result = -100;
}
else
{
$sql = "UPDATE Account SET Blocked = 0 WHERE UserId = '$user_id'";
sqlsrv_query($conn, $sql, array($user_id), array( "Scrollable" => 'static' ));
$result = 0;
}
$result = sqlsrv_get_field ($r2,0);
sqlsrv_close($conn);
}
else
{
$result = -99;
}
if (($result == -100) || ($result == -99))
{
echo '2';
die();
}
?>
That's because you didn't pass user_id and user_pass in your GET request. GET request has the parameters in a URL, so you are maybe passing them with POST request.
I have a problem with pagination and I have to admit I am a newbie for programming in php .
I hope,you can tell me how to do pagination for those codes.
index.php , homepage function.
function homepage() {
$results = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "Widget News";
require( TEMPLATE_PATH . "/homepage.php" );
}
Article.php get article function
public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS<br> publicationDate FROM articles
ORDER BY " .$order. " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
index.php show article foreach
<?php foreach ($results['articles'] as $article){?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F',$article->publicationDate)?></span>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<?php echo htmlspecialchars($article->title)?>
</a>
</h2>
<p class="summary"><?php echo htmlspecialchars($article->summary)?></p>
</li>
<?php }?>
Thank you.
You need to use OFFSET in MySql string.
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$itemsPerPage = 10;
$offset = ($page * $itemsPerPage) - $itemsPerPage;
$sql = "SELECT * FROM articles OFFSET {$offset} LIMIT {$itemsPerPage}";
Also remove <br> from your code. It's only valid for HTML, elsewhere it will throw error.
Final function (start) would look like this:
public static function getList($numRows = 10, $order = "publicationDate DESC") {
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$order = preg_replace("/[^a-zA-Z\s]/", '', $order);
$numRows = intval($numROws);
$offset = ($page * $numRows) - $numRows;
$sql = "SELECT
SQL_CALC_FOUND_ROWS *,
UNIX_TIMESTAMP(`publicationDate`) AS 'publicationDate'
FROM `articles`
ORDER BY {$order}
LIMIT :numRows
OFFSET :offset";
$st = $conn->prepare( $sql );
$st->execute(array(':numRows' => $numRows, ':offset' => $pffset));
I have some PHP that pulls all staff records in the DB.
I now want to add a clause, so it can SELECT * WHERE companyId = x.
Im using GET to retrieve the companyId to be used.
My question is, how can I pass $companyClause to the static function?
function viewStaffInCompany(){
$results = array();
$companyClause = $_GET["companyClause"];
echo $companyClause . "<br><hr>";
$data = Staff::getCompanyStaffList();
$results['staff'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( "templates/viewStaff.php" );
};
and
getCompanyStaffList();
public static function getCompanyStaffList( $numRows=1000000, $order="id ASC", $companyClause) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM Staff WHERE $companyClause ORDER BY " . $order . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$users = new Staff( $row );
$list[] = $users;
}
// Now get the total number of staff that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
Just as a parameter.
Staff::getCompanyStaffList(1000000, "id ASC", $companyClause);
But I would refactore this parameter list, because $companyClause is required, so, you will need to pass the first 2 params always, what has default values, if not given.
So it should be:
public static function getCompanyStaffList($companyClause, $numRows=1000000, $order="id ASC") {
<?php
require('db_info.php');
$recordsPerPage = 5;
if (isset($_GET['page']))
$curPage = $_GET['page'];
else
$curPage = 1;
$startIndex = ($curPage-1) * $recordsPerPage;
try {
$pdoObject = new PDO("mysql:host=$dbhost; dbname=$dbname;", $dbuser, $dbpass);
$sql = "SELECT count(id) FROM usercom";
$statement = $pdoObject->query($sql);
$record = $statement->fetch(PDO::FETCH_ASSOC);
$pages = ceil($record['count(id)']/$recordsPerPage);
$record=null;
$sql = "SELECT * FROM usercom LIMIT $startIndex, $recordsPerPage ORDER BY date DESC";
$statement = $pdoObject->query($sql);
while ( $record = $statement->fetch(PDO::FETCH_ASSOC) ) {
echo '<p>'.$record['date'].'<br/>'.$record['userComment'].'<br/>';
}
$statement->closeCursor();
$pdoObject = null;
} catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}?></p>
I'm trying to fetch result from a database and use pagination. The problem is that the descending order asked in the statement never applies. Why isn't this working? If I don't add the line "ORDER BY date DESC" it works just fine, but when I do it prints error that I'm trying to fetch a non-object.
Your syntax isn't quite correct,
Use this one instead,
$sql = "SELECT * FROM `usercom` ORDER BY `date` DESC LIMIT $startIndex, $recordsPerPage";
Can I create an array by use php variable in a loop ?
<?php
for($i=5;$i<=100;$i++)
{
$sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
$result = mysql_query($sql);
$datas=mysql_fetch_array($result);{
$username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
}
${'name' . $i} = $username;
}
?>
Okay , Now I have php variable $name1-$name100
And then I want to create array by use php variable $name1-$name100
$my_array = array(php variable $name1-$name100);
How can I do ?
Just modify how you store the username:
$my_array = array();
for ( $i = 5; $i <= 100; $i++ ) {
$sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
$result = mysql_query($sql);
$datas = mysql_fetch_array($result);
$username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
$my_array[] = $username; // push usernames into array
}
Also you shouldn't run so many queries, so I suggest something like this:
$usernames = array();
$query = "SELECT * FROM users WHERE id >= 5 AND id <= 100 ORDER BY id ASC";
$result = mysql_query( $query );
if ( mysql_num_rows( $result ) > 0 ) {
while ( $data = mysql_fetch_assoc( $result ) )
$usernames[] = stripslashes( str_replace( '\r\n', '<br>', $data['username'] ) );
}