I am trying to get the values from table and display the values in the html code.
I am working in 3 separate php files.
This is the Article.php file, which contains the Article class:
public static function getInfobar() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); //connecting to the db, the values are stored in config.php
$sql = "SELECT 'title', 'subtitle', 'additional' FROM infobar WHERE id=1";
$st = $conn->prepare ( $sql );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) { //storing the info inside the array.
$infob = new Article( $row );
$list[] = $infob;
}
$conn = null;
return ( array ( "results2" => $list));
}
After I pull these values from database, I'm trying to display them in the HTML. Firstly I declare a function inside the front-end handler: index.php
EDIT: the method is being called by using the switch.
switch ( $action )
{
default:
homepage();
}
function homepage() {
$results = array();
$results2 = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$data2 = Article::getInfobar();
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "TITLE";
$results2['info'] = $data2['results2'];
require( TEMPLATE_PATH . "/homepage.php" );
}
After, I am trying to display the values in the webpage like this:
<div class="row_item1">
<?php foreach ( $results2['info'] as $infob ) { ?>
<h1><?php echo htmlspecialchars($infob->title)?></h1>
<p><?php echo htmlspecialchars($infob->subtitle)?></p>
<p><?php echo htmlspecialchars($infob->additional)?></p>
<?php } ?>
<img src="" alt="">
</div>
But all I get is this:
I am kinda stuck here, trying to figure out what's wrong with the code for quite awhile now. Please help me out on this one. Much appreciated.
Change your query
$sql = "SELECT 'title', 'subtitle', 'additional' FROM infobar WHERE id=1";
to
$sql = "SELECT title, subtitle, additional FROM infobar WHERE id=1";
For User Requirement.
I'm not sure. But, it can be like this way. Since, i don't know the flow, i can suggest you to try like this way once.
public static function getFullInfobar() {
.
.
$sql = "SELECT title, subtitle, additional FROM infobar";
.
.
}
$results3 = array();
$data3 = Article::getFullInfobar();
$results3['info'] = $data3['results3'];
<?php foreach ( $results3['info'] as $infob ) { ?>
<div class="row_item1">
<h1><?php echo htmlspecialchars($infob->title)?></h1>
<p><?php echo htmlspecialchars($infob->subtitle)?></p>
<p><?php echo htmlspecialchars($infob->additional)?></p>
<img src="" alt="">
</div>
<?php } ?>
Related
I want to display the number of posts but unfortunately nothing is displayed. I created a function in which the query counts the number of user's posts, and then it should display this number in html, but it doesn't. I don't know where the problem is.
public function count_photos()
{
$session = $_SESSION['id'];
$query = $this->database->connect()->prepare("SELECT count(*) as photo from photo where user_id= :id");
$query->bindParam(':id',$session, PDO::PARAM_INT);
$query->execute();
if($query->rowcount())
{
while($row = $query->fetch())
{
echo $row['photo'];
}
}
}
<?php
$object = new user_statystics($object);
$post = $object->count_posts();
?>
<main>
<div>Count post:<span> <?php echo $post; ?></span></div>
</main>
I have an iOS app which I built an API to extract some data from a SQL Server database. When my app sends a query with an empty string, it doesn't return any rows, even though it should.
$connectionInfo = array( "Database"=>db, "UID"=>$user, "PWD"=>$pass);
$conn = sqlsrv_connect($ip, $connectionInfo);
if ( $conn ) {
//connected
}
else {
echo "Error:"; echo "<br>";
die( print_r( sqlsrv_errors(), true));
}
/**************************************/
/* RETRIEVAL */
/**************************************/
$prod = new StdClass(); $arr = array(); $temp = array();
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
$stmt = sqlsrv_prepare( $conn, $sql, array($search));
sqlsrv_execute( $stmt );
$i = 0;
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
else {
while ( $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
$newProd = clone $prod;
$newProd->mainInfo = $row['name'];
$newProd->secondInfo = $row['qty'];
$arr[] = $newProd;
}
}
http_response_code(200);
echo json_encode($arr);
sqlsrv_close($conn);
I built the API with PHP and Apache on macOS where it worked as intended. When I copied the files on a Windows server, if my app accessed a link similar to 192.168.0.102/file.php?search= it would return no rows on Windows, and in macOS it would return all the rows of the table, as I wanted to. I know the script works and there are no issues, because if my app accesses a link similar to 192.168.0.102/file.php?search=someName it returns the corresponding rows. I want the app to display all the rows if the variable search is empty. Should I use some other way to achieve this, or is it some mistake on my part.
you can achieve that by not using sql condition when "search" $_GET param is not supplied or is empty.
Example how to achieve that, change your code from:
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
to something like this:
$search = null;
if (true === array_key_exists('search', $_GET) && false === empty($_GET['search'])) {
$search = '%' . $_GET['search'] . '%';
}
$sql = "SELECT name, qty FROM table";
if (false === is_null($search)) {
$sql .= ' WHERE name LIKE ?';
}
(this code was updated after some answer from another topic: How do I Paginate my CMS)
I've been following the Build a CMS in an Afternoon tutorial at http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ .
The CMS works great but the only thing it's lacking is pagination. The article archive displays the list of all of the articles that are in the database, but I want to be able to separate these into pages. I've attempted it a few times but can never seem to get it to work. Clicking on a next page link usually brings me back to the homepage.
I will apreciate your help
The code:
ARTICLE
public static function getList( $numRows=130, $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 " . mysql_escape_string($order) . " LIMIT :offset, :rowCount";
$st = $conn->prepare( $sql );
$st->bindValue( ":offset", $offset, PDO::PARAM_INT );
$st->bindValue( ":rowCount", $rowCount, 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] ) );
}
$st = $conn->prepare( $sql ); $st->bindValue( ":offset", $offset, PDO::PARAM_INT ); $st->bindValue( ":rowCount", $rowCount, 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] ) ); }
ARQUIVE
<ul class="noticias_archive">
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<div class="noticias_archive col-4">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<img class="articleImageThumb" src="<?php echo $imagePath?>" alt="Article Thumbnail" />
<?php } ?></div>
<div class="noticias_archive col-4">
<h3 class="top">
<?php echo htmlspecialchars( $article->title )?>
</h3>
<p>
<?php echo htmlspecialchars( $article->summary )?><br><br><?php echo date('j F Y', $article->publicationDate)?></p>
</div>
</li>
<?php } ?>
</ul>
</div>
<p>
<?php
if ( isset( $_GET['page'] ) ){
echo sprintf('<p> << Back </p>', $_GET['page'] - 1);
echo sprintf('<p> Next >> </p>', $_GET['page'] + 1);}?> in total.</p>
<p>Return to Homepage</p>
INDEX
require( "config.php" );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
switch ( $action ) {
case 'noticias':
noticias();
break;
case 'viewArticle':
viewArticle();
break;
default:
homepage();
}
function noticias() {
$results = array();
$data = Article::getList();
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "Article Archive | teste";
require( TEMPLATE_PATH . "/archive.php" );
}
function viewArticle() {
if ( !isset($_GET["articleId"]) || !$_GET["articleId"] ) {
homepage();
return;
}
$results = array();
$results['article'] = Article::getById( (int)$_GET["articleId"] );
$results['pageTitle'] = $results['article']->title . " | teste2";
require( TEMPLATE_PATH . "/viewArticle.php" );
}
function homepage() {
$results = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "FPT - teste3";
require( TEMPLATE_PATH . "/homepage.php" );
}
im using this script through $_GET to add user name to my db beside it to my twitter list the script function well
for examlpe when i call it at url domain.com/add.php?user=username
the function of adding executed 100% fine
My doubt is about adjust the code to add multi users at once through array or get list of user from file
any tips to adjust the code or modify it ?
<?php
session_start();
require_once('dbconnect.php');
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,TOKEN_KEY, TOKEN_SECRET);
$user = $_GET['user'];
if( !isset( $_GET['user'] ) )
die('You must enter a username');
$info = $connection->get( 'users/show', array("screen_name"=> $user
));
$var = $_GET['user'];
$individual = 1;
$protected = ($info->protected == "true")?1:0;
$query = sprintf("INSERT INTO tweeps VALUES('%s', '%s', %s, %s, '%s', '%s', '%s', %s ) ",
mysql_real_escape_string($info->screen_name),
mysql_real_escape_string($info->name),
$info->followers_count,
$info->statuses_count,
mysql_real_escape_string($info->location),
$info->created_at,
$info->profile_image_url,
$protected) ;
echo $query;
$result = mysql_query($query);
if(false)
echo "s";
else {
$list_id = get_latest_list();
$list = "Tweeps-" . $list_id;
echo "list $list";
mysql_free_result($result);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$result = $connection->post( 'friendships/create/' . $info->screen_name );
//var_dump($result); die();
$result = $connection->post( 'lists/members/create', array("screen_name"=> $info->screen_name,
"slug"=> $list,
"owner_screen_name"=> "Tweeps") );
if( !isset($result->error) ) {
$userid = $info->id;
$result = mysql_query("INSERT INTO followed_tweeps(screenname, userid, individual, list_id) VALUES('" . $info->screen_name . "', '" . $userid . "', $individual, $list_id)");
}
}
echo "SUCCESS";
function get_latest_list() {
$query = "SELECT count(*) cnt, list_id FROM followed_tweeps group by list_id order by list_id desc";
$result = mysql_query($query);
if(! $result ) {
die("Error: query is $query error is: " . mysql_error() );
}
$row = mysql_fetch_row($result);
$cnt = $row[0];
$free_slots = 500 - $cnt;
$list_id = ($freeslots > 0) ? $row[1]++ : $row[1];
return $list_id;
}
?>
PHP supports an array notation for multiple same-name query parameters:
<input type="text" name="name[]" />
^^--- tells PHP to treat 'name' as an array
You can then process this as:
if (isset($_GET['name']) && isarray($_GET['name'])) {
foreach ($_GET['name'] as $name) {
...
}
}
This works regardless for both POST and GET - you just have to include the [] on the field name.
I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent