I am learning web development from "PHP and MongoDB Web Development" book. I came across these instructions for creating a blog and adding comments into it.
1)Open blog.php in your text editor and replace the existing code in it with the
following:
<?php
$id = $_GET['id'];
try {
$connection = new Mongo();
$database
= $connection->selectDB('myblogsite');
$collection = $database->selectCollection('articles');
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$article = $collection->findOne(array('_id' =>
new MongoId($id)));
?>
<!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>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
<link rel="stylesheet" href="style.css" />
<title>My Blog Site</title>
</head>
<body>
<div id="contentarea">
<div id="innercontentarea">
<h1><?php echo $article['title']; ?></h1>
<p><?php echo $article['content']; ?></p>
<div id="comment-section">
<h3>Comments</h3>
<?php if (!empty($article['comments'])): ?>
<h3>Comments</h3>
<?php foreach($article['comments'] as $comment):echo $comment['name'].' says...';?>
<p><?php echo $comment['comment']; ?></p>
<span>
<?php echo date('g:i a, F j', $comment['posted_at']->sec); ?>
</span><br/><br/><br/>
<?php endforeach;endif;?>
<h3>Post your comment</h3>
<form action="comment.php" method="post">
<span class="input-label">Name</span>
<input type="text" name="commenter_name" class="comment-input"/>
<br/><br/>
<span class="input-label">Email</span>
<input type="text" name="commenter_email" class="comment-input"/>
<br/><br/>
<textarea name="comment"vrows="5"></textarea><br/><br/>
<input type="hidden" name="article_id" value="<?php echo $article['_id']; ?>"/>
<input type="submit" name="btn_submit" value="Save"/>
</form>
</div>
</div>
</div>
</body>
</html>
2) Create comment.php file with the following code:
<?php
$id = $_POST['article_id'];
try {
$mongodb = new Mongo();
$collection = $mongodb->myblogsite->articles;
} catch (MongoConnectionException $e) {
die('Failed to connect to MongoDB '.$e->getMessage());
}
$article = $collection->findOne(array('_id' => MongoId($id)));
$comment = array('name' => $_POST['commenter_name'],'email' => $_POST['commenter_email'],'comment' => $_POST['comment'],'posted_at' => new MongoDate());
$collection->update(array('_id' => new MongoId($id)),array('push' => array('comments' => $comments)));
header('Location: blogs.php?id='.$id);
?>
3)Navigate to blogs.php in your browser, click on the Read More link of the top
article to read its full content in the blog.php page. The code for blogs.php is as follows:
<?php
try {
$connection = new Mongo();
$database
= $connection->selectDB('myblogsite');
$collection = $database->selectCollection('articles');
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$cursor = $collection->find();
?>
<!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>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
<link rel="stylesheet" href="style.css" />
<title>My Blog Site</title>
</head>
<body>
<div id="contentarea">
<div id="innercontentarea">
<h1>My Blogs</h1>
<?php while ($cursor->hasNext()):
$article = $cursor->getNext(); ?>
<h2><?php echo $article['title']; ?></h2>
<p>
<?php echo substr($article['content'], 0,
200).'...'; ?>
</p>
<a href="blog.php?id=<?php echo $article['_id'];
?>">Read more</a>
<?php endwhile; ?>
</div>
</div>
</body>
</html>
When I try to post a comment it is redirecting to a blank page. How to make this code work?
Above all code in comment.php put the following (just under the PHP opening tag):
error_reporting(E_ALL);
ini_set('display_errors', 'On');
That will show you the error that's causing the blank page and will hopefully help you on your way.
Related
I am writing the following code:
<?php
require_once("xajax/xajax_core/xajaxAIO.inc.php");
$xajax = new xajax();
function testEE($datos){
$x = $datos;
$rr = new xajaxResponse();
$rr->alert($x);
return $rr;
}
$xajax->registerFunction("testEE");
$xajax->processRequest();
?>
<!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">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test E</title>
<?php $xajax->printJavascript("xajax/"); ?>
</head>
<body>
<div id="display" style="width:750px; margin-right:auto; margin-left:auto; margin-top:100px;">
<form id='forma' name='forma'>
<table cellpadding='8' style='float:left;'>
<tr><td>Pregunta:</td><td><textarea name='question1' id='question1' cols='40' rows='8'></textarea></td></tr>
<tr><td colspan='2'><input type='button' value='Agregar' onclick="xajax_testEE(document.getElementById('question1').value)"></td></tr>
</table>
</form>
</div>
</body>
</html>
It works fine if a put a single word in the textarea but if I try to put 2 or more words it does nothing
I have tried this:
<?php
require_once("xajax/xajax_core/xajaxAIO.inc.php");
$xajax = new xajax();
function testEE($datos){
$x = $datos;
$rr = new xajaxResponse();
$rr->alert($x);
return $rr;
}
$xajax->registerFunction("testEE");
$xajax->processRequest();
?>
<!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">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test E</title>
<?php $xajax->printJavascript("xajax/"); ?>
</head>
<body>
<div id="contenido">
<div id="display" style="width:750px; margin-right:auto; margin-left:auto; margin-top:100px;">
<form id='forma' name='forma'>
<table cellpadding='8' style='float:left;'>
<tr><td>Pregunta:</td><td><textarea name='question1' id='question1' cols='40' rows='8'></textarea></td></tr>
<tr><td>Respuesta 1:</td><td><textarea name='respuesta1' id='respuesta1' cols='40' rows='8'></textarea></td></tr>
<tr><td colspan='2'><input type='button' value='Agregar' onclick="myFunction()"></td></tr>
</table>
</form>
</div>
</div>
<script>
function myFunction() {
var x = document.getElementById("question1").value;
xajax_testEE(x)
alert('myFunction alert': x)
}
</script>
</body>
</html>
When I enter a single word, I get the 2 alerts (as expected) but if I enter more than 1 word I only get the alert of myFunction with the complete string but I don't get the alert id the xajax function
The list of notes should be displayed within the ul li spans, any reason as to why they aren't showing and instead the array is showing at the top of the page?
The database connection appears to be working perfectly fine, however the notes aren't showing within the spans. It also removes the 'you haven't added any notes text'
code
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
foreach($notes as $note) {
print_r($note);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
Home
About
Contact
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
Working Code
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
Home
About
Contact
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
</div>
</body>
</html>
Feel free to use below as an example for your query.
// Your sql query
$sql = "SELECT ID, note FROM notes";
// Prepare your statement
$stmt = $db -> prepare($sql);
// Execute your prepared statement
$stmt -> execute();
// Retreive all rows
$notes = $stmt -> fetchAll();
// Check if array is not empty
if (!empty($notes)) {
//Spit out the array
print_r($notes);
}
i am try to learn kohana and have problem with kohana+ajax, console say me about response with full page+ print_r + name\phone for ajax response if run example without kohana , just php+ajax , all ok
UPD:
wait: name: $name ,phone:$phonenumber.
recieve(look console.log): page from main template + print_r+ response for ajax and name:undefined,
phone: undefined.
here code for reproducing the behaviour:
Controller/example.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Example extends Controller_Common
{
public function action_index()
{
$content = View::factory('/example/show')
->bind('example', $example)
->bind('errors', $errors);
if ($this->request->is_ajax()) {
if (isset($_POST["name"]) && isset($_POST["phonenumber"]) ) {
$result = array(
'name' => $_POST["name"],
'phonenumber' => $_POST["phonenumber"]
);
print_r($result);
echo json_encode($result);
}
}
else $this->template->content=$content;
}}
View:
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<form method="post" id="ajax_form" action="" >
<input type="text" name="name" placeholder="NAME" /><br>
<input type="text" name="phonenumber" placeholder="YOUR PHONE" /><br>
<input type="button" id="btn" value="send" />
</form>
<br>
<div id="result_form"></div>
</body>
</html>
<script>
$( document ).ready(function() {
$("#btn").click(
function(){
sendAjaxForm('result_form', 'ajax_form');
return false;
}
);
});
function sendAjaxForm(result_form, ajax_form) {
jQuery.ajax({
url: '',
type: "POST",
dataType: "html",
data: jQuery("#"+ajax_form).serialize(),
success: function(response) {
//console.log(response);
//result = jQuery.parseJSON(response);
result = response;
console.log(result);
document.getElementById(result_form).innerHTML = "name: "+result.name+"<br>phone: "+result.phonenumber;
},
error: function(response) {
document.getElementById(result_form).innerHTML = "Error";
}
});
}
</script>
Controller/Common:
<?php defined('SYSPATH') or die('No direct script access.');
abstract class Controller_Common extends Controller_Template {
public $template = 'main';
public function before()
{
parent::before();
View::set_global('title', 'My Site');
View::set_global('description', 'My Site');
$this->template->content = '';
$this->template->styles = array('main');
$this->template->scripts = '';
}
} // End Common
Main Template View:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $description; ?>" />
<?php foreach($styles as $style): ?>
<link href="<?php echo URL::base(); ?>public/css/<?php echo $style; ?>.css"
rel="stylesheet" type="text/css" />
<?php endforeach; ?>
</head>
<body>
<div class="layer">
<div class="container">
<div class="header"><h1>Logo</h1></div>
<div class="left">
<h3>Menu</h3>
<br />
<ul>
<li>Home</li>
<li>about</li>
<li>Reg</li>
<li>contacts</li>
<li>Articles</li>
</ul>
<li>Article1</li>
<li>Article2</li></ul>
</div>
<div class="content"><?php echo $content; ?></div>
<div class="clearing"></div>
<div class="footer">2011 All rights reserved</div>
</div>
</div>
</body>
</html>
Console.log :
Array
(
[name] => 1
[phonenumber] => 1
)
{"name":"1","phonenumber":"1"}<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My site</title>
<meta name="description" content="My site" />
<link href="/public/css/main.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<div class="layer">
<div class="container">
<div class="header"><h1>Logo</h1></div>
<div class="left">
<h3>Menu</h3>
<br />
<ul>
<li>Home</li>
<li>about</li>
<li>Reg</li>
<li>contacts</li>
<li>articles</li>
</ul>
<li>article1</li>
<li>article2</li></ul>
</div>
<div class="content"></div>
<div class="clearing"></div>
<div class="footer">2011 All rights reserved</div>
</div>
</div>
</body>
</html>
problem solved, get anwer from :
autor: croll ,
Source
after json_encode(); add exit; // for unknown reasons, the main template was attached to the answer for ajax and exit; fix it.
and result = response;=>result = jQuery.parseJSON(response); // for decode ajax answer
I am working on a little forum, and I want it to be easy to identify a staff member.
A the moment, a user is defined as an $admin in the config file:
<?php
/******************************************************
------------------Required Configuration---------------
Please edit the following variables so the forum can
work correctly.
******************************************************/
//We log to the DataBase
mysql_connect('127.0.0.1', 'root', '');
mysql_select_db('forum_database');
//Forum Staff
$admin='The_Darthonian'; // For admin forum features
/******************************************************
-----------------Optional Configuration----------------
******************************************************/
//Forum Home Page
$url_home = 'index.php';
//Design Name
$design = 'default';
/******************************************************
----------------------Initialization-------------------
******************************************************/
include('init.php');
?>
I have an icon at the path of default/images/role_moderator.gif that I want to appear on a profile if a user is defined as an admin
I further have a userid variable. For example, the first account would be 1, then the second 2 and so on which are unique. Below is the profile code:
<?php
//This page display the profile of an user
include('config.php');
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $design; ?>/style.css" rel="stylesheet" title="Style" />
<title>User Profile</title>
</head>
<body>
<div class="header">
<img src="<?php echo $design; ?>/images/logo.png" alt="Forum" />
</div>
<div class="content">
<?php
if(isset($_SESSION['username']))
{
$nb_new_pm = mysql_fetch_array(mysql_query('select count(*) as nb_new_pm from pm where ((user1="'.$_SESSION['userid'].'" and user1read="no") or (user2="'.$_SESSION['userid'].'" and user2read="no")) and id2="1"'));
$nb_new_pm = $nb_new_pm['nb_new_pm'];
?>
<div class="box">
<div class="box_left">
Home > Users > Profile
</div>
<div class="box_right">
Your messages(<?php echo $nb_new_pm; ?>) - <?php echo htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?> (Logout)
</div>
<div class="clean"></div>
</div>
<?php
}
else
{
?>
<div class="box">
<div class="box_left">
Home > Users > Profile
</div>
<div class="box_right">
Sign Up - Login
</div>
<div class="clean"></div>
</div>
<?php
}
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
$dn = mysql_query('select username, email, avatar, signup_date from users where id="'.$id.'"');
if(mysql_num_rows($dn)>0)
{
$dnn = mysql_fetch_array($dn);
?>
This is the profile of "<?php echo htmlentities($dnn['username']); ?>" :
<?php
if($_SESSION['userid']==$id)
{
?>
<br /><div class="center">Edit my profile</div>
<?php
}
?>
<table style="width:500px;">
<tr>
<td><?php
if($dnn['avatar']!='')
{
echo '<img src="'.htmlentities($dnn['avatar'], ENT_QUOTES, 'UTF-8').'" alt="Avatar" style="max-width:100px;max-height:100px;" />';
}
else
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
</head>
<body>
<?php
?>
<div>
<img src="default/images/no_avatar.jpg" alt="no_avatar" />
</div>
</body>
</html>
<?php
}
?></td>
<td class="left"><h1><?php echo htmlentities($dnn['username'], ENT_QUOTES, 'UTF-8'); ?></h1>
This user joined the website on <?php echo date('Y/m/d',$dnn['signup_date']); ?></td>
</tr>
</table>
<?php
if(isset($_SESSION['username']) and $_SESSION['username']!=$dnn['username'])
{
?>
<br />Message "<?php echo htmlentities($dnn['username'], ENT_QUOTES, 'UTF-8'); ?>"
<?php
}
}
else
{
echo 'We could not find this user anywhere. Prehaps their account was removed.';
}
}
else
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
</head>
<body>
<?php
?>
<div>
<img src="/default/images/no_avatar.jpg" alt="no_avatar" />
</div>
</body>
</html>
<?php
}
?>
</div>
<div class="foot">About Us - Terms of Service</div>
</body>
</html>
How can I make it so that if a user is defined as an $admin in the config, they have the icon appear on their profile?
I have a webpage and a place to submit data. I made a preview page for this, and whenever a user clicks 'preview' he can see what it would look like. The trouble is whenever they click the back button from the preview all the data is gone. How do I avoid this and keep the data without any very complex solutions?
preview.php
<?php
session_start();
$getTitle = $_POST['title'];
$getEntry = $_POST['entry'];
date_default_timezone_set('UTC');
$getTime = date('D, M jS, o, H:i a e');
$user = $_SESSION['username'];
?>
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<link rel="stylesheet" type="text/css" href="css/main.css">
<head> <title> Blog - Preview </title> </head>
<body>
<div class="wrap">
<div class="navPreview">
<ul>
<li>Back<br></li>
</ul>
</div>
<div class="main">
<h1>Preview</h1>
<div class="mainscroll">
<?php
echo "<span>Submitted at: $getTime by $user</span><br>";
echo "<h2>$getTitle</h2>";
echo "<p>$getEntry</p><hr>";
?>
</div>
</div>
</div>
<div class="footer">x</div>
</body>
addentry.html
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<link rel="stylesheet" type="text/css" href="css/main.css">
<head> <title> Blog - Add Entry </title> </head>
<body>
<div class="wrap">
<div class="header">
<h2> Welcome.. </h2>
<p>..add an entry below</p>
</div>
<div class="nav">
<ul>
<li>Home<br></li>
<li>Add Entry<br></li>
<li>Logout<br></li>
</ul>
</div>
<div class="main">
<form id="entryForm" action="addentry.php" method="post">
<p class="title">
<label>Title:</label>
<input type="text" name="title"><br>
</p>
<p class="body">
<label>Entry:</label>
<textarea name="entry"></textarea><br>
</p>
<p class = "buttons">
<script type="text/javascript">
function clearConfirm() {
var confirm = window.confirm("Are you sure you want to clear?");
if (confirm) {
document.getElementById("entryForm").reset();
}
}
function previewForm(action) { document.getElementById('entryForm').action = action;
document.getElementById('entryForm').submit();
}
</script>
<input type="button" onclick="clearConfirm()" value="Clear" />
<input type="button" onclick="previewForm('preview.php')" value="Preview" />
<input type="submit" value="Submit" />
</p>
</form>
</div>
<div class="footer">x</div>
</div>
Maybe add a target="_blank" ? It will open the preview in a new tab.
<input type="button" onclick="previewForm('preview.php')" value="Preview" target="_blank"/>
EDIT: Oups not in the form but on your preview link...
Or something like this : http://www.w3schools.com/tags/att_button_formtarget.asp