Retrieving Google Contacts Using Zend - php

I see this tutorial referenced a lot for how to retrieve Google Contacts using PHP. It says that all you have to do is install Zend and then start using the code examples provided.
I installed Zend (I think). Then tried the code below, from the tutorial, and replaced user#gmail.com with my Gmail address and guessme with my Gmail password, thinking that the code below would return all of my Gmail contacts. But it just returns a blank screen.
Does this mean I didn't install Zend correctly?
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Listing contacts</title>
<style>
body {
font-family: Verdana;
}
div.name {
color: red;
text-decoration: none;
font-weight: bolder;
}
div.entry {
display: inline;
float: left;
width: 400px;
height: 150px;
border: 2px solid;
margin: 10px;
padding: 5px;
}
td {
vertical-align: top;
}
</style>
</head>
<body>
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Feed');
// set credentials for ClientLogin authentication
$user = "user#gmail.com";
$pass = "guessme";
try {
// perform login and set protocol version to 3.0
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'cp');
$gdata = new Zend_Gdata($client);
$gdata->setMajorProtocolVersion(3);
// perform query and get result feed
$query = new Zend_Gdata_Query(
'http://www.google.com/m8/feeds/contacts/default/full');
$feed = $gdata->getFeed($query);
// display title and result count
?>
<h2><?php echo $feed->title; ?></h2>
<div>
<?php echo $feed->totalResults; ?> contact(s) found.
</div>
<?php
// parse feed and extract contact information
// into simpler objects
$results = array();
foreach($feed as $entry){
$xml = simplexml_load_string($entry->getXML());
$obj = new stdClass;
$obj->name = (string) $entry->title;
$obj->orgName = (string) $xml->organization->orgName;
$obj->orgTitle = (string) $xml->organization->orgTitle;
foreach ($xml->email as $e) {
$obj->emailAddress[] = (string) $e['address'];
}
foreach ($xml->phoneNumber as $p) {
$obj->phoneNumber[] = (string) $p;
}
foreach ($xml->website as $w) {
$obj->website[] = (string) $w['href'];
}
$results[] = $obj;
}
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
<?php
// display results
foreach ($results as $r) {
?>
<div class="entry">
<div class="name"><?php echo (!empty($r->name)) ?
$r->name : 'Name not available'; ?></div>
<div class="data">
<table>
<tr>
<td>Organization</td>
<td><?php echo $r->orgName; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo #join(', ', $r->emailAddress); ?></td>
</tr>
<tr>
<td>Phone</td>
<td><?php echo #join(', ', $r->phoneNumber); ?></td>
</tr>
<tr>
<td>Web</td>
<td><?php echo #join(', ', $r->website); ?></td>
</tr>
</table>
</div>
</div>
<?php
}
?>
</body>
</html>

Did you update your php.ini include path to point to the Zend library.
Say you unpacked the library to C:\ZendXXX\library\Zend.
Add this to your php.ini file
include_path=".;C:\ZendXXX\library";

Related

Php Error Message " Uncaught exception 'Exception' with message 'Query Failed:Array"

I tried to render a table from MS-SQL Database to Webpage and i get this error.
I'm still new in PHP. Please help
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"])
?>
Error Displayed
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 26
Notice: Array to string conversion in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Fatal error: Uncaught exception 'Exception' with message 'Query Failed:Array' in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php:29 Stack trace: #0 C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php(8): SimpleUsers->getUsers() #1 {main} thrown in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Your conn class property is not set.
Before you call $stmt = sqlsrv_query($this->conn, $sql); you must set it up in sqlsrv_connect.
Try adding construct:
public function __construct()
{
$this->conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
}
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public $conn=$GLOBALS["conn"] ;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$GLOBALS["conn"] = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"] );
?>
Hope it will help.
I have these two items in my php.ini file enabled:
extension=php_pdo_sqlsrv_53_ts.dll
extension=php_sqlsrv_53_ts.dll
Which is what I had before. Using Wamp Server. PHP 5.3.13 all the same as before. What else am I missing that is not allowing this to connect to the SQL server.
After connection file code.
<?php
$GLOBALS["serverName"] = "localhost";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "root";
$GLOBALS["pwd"] = "";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
?>

Dompdf is not printing the table with posted php form

When I try to print the table in the file_html.php it prints the static table with some error(that's a different question). However, when the php tags for the posted data are included in the file with the post variables, the pdf generated displays nothing at all except for the anchor tag which is at the bottom of the page.
Here is the index.php :-
require_once("dompdf/dompdf_config.inc.php");
require_once("dompdf/dompdf_config.custom.inc.php");
spl_autoload_register('DOMPDF_autoload');
function pdf_create($html, $filename, $paper, $orientation, $stream=TRUE)
{
$dompdf = new DOMPDF();
$dompdf->set_paper($paper,$orientation);
$dompdf->load_html_file('http://localhost/pdf/file_html.php');
$dompdf->render();
$dompdf->stream($filename.".pdf");
}
$filename = 'billofsale';
$dompdf = new DOMPDF();
$html = file_get_contents('http://localhost/pdf/file_html.php');
pdf_create($html,$filename,'A4','portrait');
And here is the file_html.php which consists the form with the post variable. Note : when the php with the post is removed the table prints out in the pdf.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
}
table {
border-collapse: collapse;
border-spacing: 0;
width:100%;
}
body{
font: normal medium/1.4 sans-serif;
}
th{
text-align: center;
border: 3px solid #ccd;
}
td{
padding: 0.25rem;
text-align: left;
border: 2px solid #ccc;
}
tbody tr:nth-child(odd){
background: #eee;
}
tbody:before, thead:after { display: none; }
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
?>
<p>
<table>
<thead><th colspan="2">Purchaser's Information</th></thead>
<tbody>
<tr>
<td colspan="2">Purchaser's Name : <?php echo $_POST['pname']; ?></td>
</tr>
<tr>
<td colspan="2">Purchaser's Address : <?php echo $_POST['padd']; ?></td>
</tr>
<tr>
<td>City/Town : <?php echo $_POST['pcity']; ?> </td>
<td>Province : <?php echo $_POST['ppro']; ?></td>
</tr>
<tr>
<td>Postal Code :<?php echo $_POST['ppcode']; ?></td>
<td>Home Tel No :<?php echo $_POST['ptelno']; ?></td>
</tr>
<tr>
<td>Business Tel :<?php echo $_POST['pbtel']; ?></td>
<td>Email :<?php echo $_POST['pemail']; ?></td>
</tr>
<tr>
<td>Driver License : <?php echo $_POST['pdriverlic']; ?></td>
<td>Expiry Date :<?php echo $_POST['pdriverexp']; ?></td>
</tr>
</tbody>
</table>
</p>
<?php
}
?>
Print
</body>
</html>
You're loading file_html.php using $dompdf->load_html_file('http://localhost/pdf/file_html.php');. This method is like starting a new browser request using the GET method. Any variables set during the current PHP process are not passed through. This means the $_POST array is empty.
There are a few ways of addressing the issue, but since your table relies on data from the $_POST array I'd suggest using output buffering. You can render the content within index.php, capture the output, and feed it to dompdf.
Using your original sample as a starting point ...
<?php
ob_start();
require 'file_html.php'
$html = ob_get_contents();
ob_end_clean();
require_once('dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream('billofsale.pdf');
?>
Now when you POST to index.php the $_POST array will be available to file_html.php.

get first object from result array php

I have view file on my app there is code array I want to get first object of that array without going in loop.
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
$result is array of object I'm getting from a form. In below you can clearly see I'm chunking it to 3 more array and looping though individual objects and getting their details to html for example.
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
I want to get the first object details let's say want get $product->product_name of first object of result array without going in loop how to achieve that.
here is complete view file code.
<!DOCTYPE html>
<html class="bg-black">
<head>
<meta charset="UTF-8">
<title><?php if(isset($title)) echo $title.' | '; ?> Sales agent management software (SAMS) </title>
<style>
body{
font-size: 9px;
margin: 20px;
}
th,td,p,div,table,h3{margin:0;padding:0}
#page { margin: 20px; }
.header{
border-bottom: 0px solid #dddddd;
text-align: center;
position: fixed; top: 0;
}
.footer { position: fixed; bottom: 0px; text-align: center }
.pagenum:before { content: counter(page); }
</style>
</head>
<body>
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<div class="footer">
Page: <span class="pagenum"></span>, creation time : <?php echo date('l jS \of F Y h:i:s A') ?>, create by: <?php echo user_full_name(singleDbTableRow(loggedInUserData()['user_id'])); ?>, $ Rate : Rs. <?php echo $usd; ?> </div>
<br />
<div class="box-body">
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
<tr>
<th><FONT SIZE=12>LKR</FONT></th>
<td><FONT SIZE=14><?php $lkr = get_selling_price($product);
echo number_format(round($lkr, get_option('round_precision')) ); ?></FONT>
</td>
</tr>
<tr>
<th> <FONT SIZE=12>US $</FONT></th>
<td><FONT SIZE=14><?php echo number_format(round(lkr_to_usd($lkr), get_option('round_precision')) ); ?></FONT></td>
</tr>
</table>
<?php $GLOBALS['a']= $product->product_id; ?>
</div>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
</div><!-- /.box-body -->
</body>
</body>
</html>
ok man as i said u need to change your way of writing codes but about your specific question use this:
$result = array('a', 'b', 'c', 'd', 'e');
reset($array);
$first = current($array);
you can check this:
http://php.net/manual/en/function.reset.php
http://php.net/manual/en/function.current.php
But still about your way of coding. u should soon go to MVC or such ways of programming so u should separate your view and coding logics
like u may have a page like view_profile.php which is going to show user's information. in regular coding u have this:
view_profile.php:
<?php session_start();
// you check sessions to see if the user is logged in and has the right to view this page.
// like:
if ($_SESSIONS['is_user_logged_in']){
$username=$_SESSIONS['username'];
$name=$_SESSIONS['name'];
// ....
}else{
header('location: ./login.php');// if user is not authenticated u redirect to login page
exit();// prevents the rest of codes to be shown and executed
}
?>
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
But in a better way u can do it like this:
you have files like
'view_profile.htm' // holds the HTML
'view_profile.php // holds the PHP logic
'inc.php' // holds some useful functions that help you in writing PHP logic
view_profile.htm
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
inc.php
<?php
function ses_start(){
if(!session_id()){
session_start();
}
}
function ses_get($key){
ses_start();
if(!empty($_SESSION[$key])){
return $_SESSION[$key];
}
return NULL;
}
function ses_set($key,$val){
$_SESSION[$key]=$val;
}
function is_user_loggedin(){
ses_start();
if(!empty(ses_get('is_user_loggedin')){
return true;
}
return false;
}
function go($to){
header('location: '.$to);
exit();
}
//and lots of useful functions that help u connect and work with data base.
view_profile.php
<?php
include('inc.php');
if(is_user_loggedin(){
$username=ses_get('username');
$name=ses_get('name');
//...
}else{
go('login.php);
}
include('view_profile.html); // and u call the .htm file that holds the HTML the view file)
?>
this was a simple sample of separating codes logic(php codes) from views(html tags)
and also u may search about MVC Model-View-Controller and try working with simple MVC frameworks.

Error in mysqli after pagination

It's me again, sorry...
I've been looking for the answer right in this forums, but there are no posts has been solved. I don't know if the questioner has been resolved the problems and not given a solved comment or something like that. All the comments/replies from the questioner is 'not work' or 'get some new errors' ect.
Now my scripts has worked before I put pagination scripts on them, but again errors in 'mysqli'. The errors are:
Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\paging\index.php on line 8
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\paging\index.php on line 9
My scripts contained two files:
index.php:
<?php
$con = mysqli_connect("localhost", "root", "", "db_book") or die(mysqli_error($con));
$per_page = 3;
//getting number of rows and calculating no of pages
$sql = "SELECT COUNT(*) FROM flipbook";
$result = mysqli_query($sql);
$count = mysqli_fetch_row($result);
$pages = ceil($count[0]/$per_page);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>DIGITAL LIBRARY</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pagination.js"></script>
<style>
body { margin: 0; padding: 0; font-family:Verdana; font-size:15px }
a
{
text-decoration:none;
color:#B2b2b2;
}
a:hover
{
color:#DF3D82;
text-decoration:underline;
}
#loading {
width: 100%;
position: absolute;
}
#pagination
{
text-align:center;
margin-left:120px;
}
li{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
</style>
</head>
<body>
<div align="center">
<div style="margin-top:50px;"></div>
<div id="content" ></div>
<table width="800px">
<tr><Td>
<ul id="pagination">
<?php
//Show page links
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
</Td>
</tr></table>
<div id="loading" ></div>
</div>
</body>
</html>
and data.php:
<?php
$con = mysqli_connect("localhost", "root", "", "db_book");
$sql = mysqli_query($con,"SELECT b.*, title, author_name, url_flipbook, p.publisher_name, ct.cat_name FROM biblioflip AS b
LEFT JOIN mst_publisherflip AS p ON b.publisher_id=p.publisher_id
LEFT JOIN mst_catflip AS ct ON b.cat_id=ct.cat_id
ORDER BY flip_id limit $start,$per_page") or die(mysqli_error($con));
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
//getting table contents
$start = ($page-1)*$per_page;
?>
<table id="tbl">
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Category</th>
<th>Link</th>
<?php
while($row = mysqli_fetch_array($result))
{
$title = $row['title'];
$author = $row['author_name'];
$publisher = $row['publisher_name'];
$category = $row['cat_name'];
$link = 'FLIPBOOK</td>';
?>
<tr>
<td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $publisher; ?></td>
<td><?php echo $category; ?></td>
<td><?php echo $link; ?></td>
</tr>
<?php
} //End while
mysqli_close($con);
?>
</table>
<style>
#tbl
{
width:800px;
border:1px solid #98bf21;
margin-top:50px;
}
#tbl tr:nth-child(odd) {
background: #EAF2D3
}
#tbl td{
border:1px solid #98bf21
}
#tbl th
{
background: #A7C942;
border:1px solid #98bf21
}
</style>
Thanks again...thank you...
best regards,
The error message is quite descriptive and clear: The first parameter to mysqli_query should be the connection handle.
Instead of $result = mysqli_query($sql);, use $result = mysqli_query($con, $sql);

Creating a 'grid' using HTML tables within a PHP foreach loop

I've been working with Twitter with the intention of grabbing a user's followers and displaying them in a grid format. The picture below illustrates how I'd like the output to be arranged:
The code that I currently have attempts to use HTML tables, however it just prints out the name, then the picture underneath and so on. I have a feeling I might have to use nested tables or something but I can't figure it out. Here is my code:
<table>
<?php foreach ($users as $user) {
$userScreenName = $user -> screen_name;
$userName = $user -> name;
$userImage = $user -> profile_image_url;
$userDescription = $user -> description;
?>
<tr>
<td>
<?php echo $userName; ?>
</td>
</tr>
<tr>
<td>
<?php echo "<img src = ".$userImage.">"; ?>
</td>
</tr>
<?php
}
?>
</table>
How can I make my output look like my picture (small blocks of name above picture arranged side by side in a grid)?
i would rather use divs insted of tables, because u dont have to create as many columns as you want in your grid, just change the width of one element and they show next to each other, depends on the parents element width.
here is example: grids example
so your code wil look like this
<?php foreach ($users as $user) {
$userScreenName = $user -> screen_name;
$userName = $user -> name;
$userImage = $user -> profile_image_url;
$userDescription = $user -> description;
?>
<div class="name">
<?php echo $userName; ?>
<div class="picture">
<img src="./PATH/<?php echo $userImage; ?>" />
</div>
</div>
<?}?>
<style>
.name {
position:relative;
float:left;
width: 49%;
height: 100px;
border: 1px solid;
text-align:center;
vertical-align:middle;
}
.picture {
width: 80%;
height: 60%;
display: table;
margin: 0 auto;
border: 1px solid;
}
</style>
hope it helps. And sorry for my english :)
<table>
<?php foreach ($users as $user) {
$userScreenName = $user -> screen_name;
$userName = $user -> name;
$userImage = $user -> profile_image_url;
$userDescription = $user -> description;
?>
<tr>
<td>
<?php echo $userName; ?>
</td>
<td>
<?php echo "<img src = ".$userImage.">"; ?>
</td>
</tr>
<?php
}
?>
</table>
Keep in mind that if you have an odd number of friends to add then the LAST table celle will need to be added and be blank
So to give you a pseudo code example you would end up with something like
<table>
<tr>
<td>
<!-- your data here -->
</td>
If NumberOfFriends Mod 2 > 0 Then
<td>
<!-- your data here -->
</td>
Else
<td>
<!-- Blank table cell here -->
</td>
End of If statement
</tr>
</table>
You need to display every alternate user with slightly different markup. Users with even numbered indices will be displayed as the first td element in a row, while users with odd numbered indices will be displayed as the second td in the row.
<table>
<?php foreach ($users as $i => $user) {
$userScreenName = $user -> screen_name;
$userName = $user -> name;
$userImage = $user -> profile_image_url;
$userDescription = $user -> description;
if ($i % 2 == 0) :
?>
<tr>
<td>
<?php
echo $userName;
echo "<img src = ".$userImage.">";
?>
</td>
<?php else : ?>
<td>
<?php
echo $userName;
echo "<img src = ".$userImage.">";
?>
</td>
</tr>
<?php
endif;
}
?>
<div id="container">
<?php foreach ($users as $user) {
$userScreenName = $user -> screen_name;
$userName = $user -> name;
$userImage = $user -> profile_image_url;
$userDescription = $user -> description;
?>
<div class="user">
<div class="user_name">
<?php echo $userName; ?>
</div>
<div class="user_image">
<?php echo "<img src = ".$userImage.">"; ?>
</div>
</div>
<?php
}
?>
</div>
And your css would be like the following:
#container
{
width: 400px;
}
.user
{
float: left;
width:50%;
}
.user_name, .user_image
{
width: 100%;
}
why not include a div inside the table's cells, with a span for the name and a start a new line with css or a br? you can centre the cell's contents with CSS
Try to output something like this:
<table>
<tr>
<td>
<div>
<span class="user-name">NAME</span>
<img class="user-face" src=""/>
</div>
</td>
<td>
<div>
<span class="user-name">NAME</span>
<img class="user-face" src=""/>
</div>
</td>
</tr>
</table>
and the styles:
.user-name {
width: 10em;
display: table-cell;
text-align: center;
}
.user-face {
width: 10em;
height: 10em;
}
Assuming of course that they have an even number of friends... :) You'll have to add an empty td to the end if not!
EDIT: this time based entirely on divs and including the PHP. Will handle odd numbers of friends too :)
<div id="user-data">
<?php
$cellPosition = "left";
foreach ($users as $user) {
$userScreenName = $user->screen_name;
$userName = $user->name;
$userImage = $user->profile_image_url;
$userDescription = $user->description;
if ($cellPosition == "left") {
echo "<div class=\"user-table-row\">\n";
}
echo "<div class=\"cell $cellPosition\">\n";
echo " <span class=\"user-name\">$userName</span>\n";
echo " <img class=\"user-face\" src=\"$userImage\"/>\n";
echo "</div>";
if ($cellPosition == "right") {
echo "</div>";
$cellPosition = "left";
}
else {
$cellPosition = "right";
}
}
?>
</div>
the styles:
<style>
#user-data {
margin:2em;
}
div.user-table-row {
margin: 2em;
width: 24em;
clear: right;
}
div.cell {
width:10em;
display: table-cell;
text-align: center;
margin-bottom: 2em;
}
div.left {
float: left;
}
div.right {
float: right;
}
span.user-name {
width: 10em;
}
img.user-face {
width: 10em;
height: 10em;
}
</style>

Categories