Thanks in advance.
I am trying to update information in my db but am having no luck and no error messages.
Here is the page code (the pid or post_id is in the URL):
<?php
include('page with functions.php');
if (isset($_GET['pid'], $_POST['title'], $_POST['body'])){
if (edit_post($_GET['pid'], $_POST['title'], $_POST['body'])){
header("Location: blog_edit.php?pid={$_GET['pid']}");
}else{
header("Location: some location.php");
}
die();
}
?>
<!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>Blog Edit</title>
</head>
<body>
<div>
<?php
if (isset($_GET['pid']) ===false || valid_pid($_GET['pid']) === false){
echo 'Invalid post ID';
}else{
$post = get_post($_GET['pid']);
?>
<h2><?php echo $post['title']; ?></h2>
<hr />
<p><?php echo $post['body']; ?></p>
<hr />
<form action="" method="post">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="<?php echo $post['title']; ?>"/>
</p>
<p>
<textarea name="body" rows="20" cols="60"><?php echo $post['body']; ?></textarea>
</p>
<p>
<input type="submit" value="Edit Post" />
</p>
</form>
<?php
}
?>
</div>
</body>
</html>
Here is the function (the pid or post_id is in the URL):
// edits a blog entry
function edit_post($title, $body){
$title = mysql_real_escape_string(htmlentities($title));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("UPDATE `posts` (`post_title`, `post_body`) SET `post_title` = '{$title}' AND `post_body` = '{body}' WHERE `post_id` = {$pid}");
}
Any help would be great thanks!
FYI I am new to PHP MYSQL so please be kind.
if (edit_post($_GET['pid'], $_POST['title'], $_POST['body'])){
header("Location: blog_edit.php?pid={$_GET['pid']}");
}else{
header("Location: some location.php");
}
You're passing three arguments in the function call, but the function definition has only 2 arguments.
function edit_post($title, $body){
$title = mysql_real_escape_string(htmlentities($title));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("UPDATE `posts` (`post_title`, `post_body`) SET `post_title` = '{$title}' AND `post_body` = '{body}' WHERE `post_id` = {$pid}");
}
Also, return a boolean from the function.
function edit_post($pid, $title, $body){
$title = mysql_real_escape_string(htmlentities($title));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
$result = mysql_query("UPDATE `posts` (`post_title`, `post_body`) SET `post_title` = '{$title}' AND `post_body` = '{body}' WHERE `post_id` = {$pid}");
echo $result;
}
Related
i have two html forms on same page and on top of each form there is an input field that is intended to give each form a serial no.
i am using phpdesktop chrome with html5, php, and sqlite3 to show a 6 digit no from orders.db database in an input field
here is my code that i am using
forms.php
<?php
session_start();
class DBUtil extends SQLite3 {
function __construct() {
//Open db
$this->open("orders.db");
}
function createTableIfNotExists() {
//create table if not exists already
$sql = "CREATE TABLE IF NOT EXISTS order_sequence (" . " next_seq INT NOT NULL" . ")";
$result = $this->exec($sql);
return $result; //Whether table created successfully or not
}
function updateNextSeqNumber($nextSeq) {
//update next sequnce number in db
$sql = "UPDATE order_sequence SET next_seq = " . $nextSeq;
$result = $this->exec($sql);
return $result;
}
function insertFirstTime() {
//insert first time
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
$result = $this->exec($sql);
return $result;
}
function getNextSeq() {
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$result = $this->query($sql);
$nextSeq = 1;
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$nextSeq = $row["next_seq"];
} else {
$this->insertFirstTime(); //First sequence number, so that next update queries will be always successfull
}
$this->updateNextSeqNumber($nextSeq + 1);
return $nextSeq;
}
}
function getNextSequnceNumber() {
//Create new object of utility class
$db = new DBUtil();
if (!$db) {
die("Connection failed: " . $db->lastErrorMsg());
}
//Check if connected
if ($db->createTableIfNotExists()) {
$nextSeq = $db->getNextSeq();
return formatToSixCharacters($nextSeq);
} else {
die("Error: " . $db->lastErrorMsg());
}
//close connection finally
$db->close();
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if (strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for ($i = 1;$i <= $zeros;$i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!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 content="text/html; charset=utf-8" http-equiv=Content-Type>
<title></title>
</head>
<body>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-1)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6">
</div>
</div>
</div>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-2)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6">
</div>
</div>
</div>
</body>
</html>
and this above code is working fine except one problem and the problem is that it shows 000001 in form-1 input field and then add 1 and shows 000002 in form-2 but i want it to show same serial no on both forms e.g 000001 on form-1 and also 000001 on form-2 thats it!
since i know little about php and sqlite i cann't figure it out.
any help will be really appreciated.
ps: i don't want to change the nature of the code because every time i clicked on the link to that page it increases serial no by one in the input field.
Each time you're calling getNextSequnceNumber() you are incrementing the value. You want to store the sequence number in a variable once and then use that variable in multiple places.
Also, the way your code is setup, it will increment on every page load.
...
<?php
$sequenceNumber = getNextSequnceNumber();
?>
<!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 content="text/html; charset=utf-8" http-equiv=Content-Type>
<title></title>
</head>
<body>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-1)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname" value="<?php echo $sequenceNumber; ?>" maxlength="6" size="6">
</div>
</div>
</div>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-2)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname" value="<?php echo $sequenceNumber; ?>" maxlength="6" size="6">
</div>
</div>
</div>
</body>
</html>
EDIT
<?php
session_start();
class DBUtil extends SQLite3
{
function __construct()
{
//Open db
$this->open("orders.db");
}
function createTableIfNotExists()
{
//create table if not exists already
$sql = "CREATE TABLE IF NOT EXISTS order_sequence (" . " next_seq INT NOT NULL" . ")";
$result = $this->exec($sql);
return $result; //Whether table created successfully or not
}
function updateNextSeqNumber($nextSeq)
{
//update next sequnce number in db
$sql = "UPDATE order_sequence SET next_seq = " . $nextSeq;
$result = $this->exec($sql);
return $result;
}
function insertFirstTime()
{
//insert first time
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
$result = $this->exec($sql);
return $result;
}
function getNextSeq()
{
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$result = $this->query($sql);
$nextSeq = 1;
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$nextSeq = $row["next_seq"];
} else {
$this->insertFirstTime(); //First sequence number, so that next update queries will be always successfull
}
$this->updateNextSeqNumber($nextSeq + 1);
return $nextSeq;
}
}
function getNextSequnceNumber()
{
//Create new object of utility class
$db = new DBUtil();
if (!$db) {
die("Connection failed: " . $db->lastErrorMsg());
}
//Check if connected
if ($db->createTableIfNotExists()) {
$nextSeq = $db->getNextSeq();
return formatToSixCharacters($nextSeq);
} else {
die("Error: " . $db->lastErrorMsg());
}
//close connection finally
$db->close();
}
function formatToSixCharacters($num)
{
$numStr = $num . "";
if (strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for ($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
$sequenceNumber = getNextSequnceNumber();
?>
<!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 content="text/html; charset=utf-8" http-equiv=Content-Type>
<title></title>
</head>
<body>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-1)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname"
value="<?php echo $sequenceNumber; ?>" maxlength="6" size="6">
</div>
</div>
</div>
<!-- form-2 -->
<div class="grid">
<div class="grid-m1">
<div class="grid-c1">
<h2 class="form-no">(form-2)</h2>
<input id="division-no" class="serial-no division-no" type="text" name="fname"
value="<?php echo $sequenceNumber; ?>" maxlength="6" size="6">
</div>
</div>
</div>
</body>
</html>
I have 2 tables
TABLE joke (id, joke_text, joke_date, author_id)
TABLE author(id, name, email)
I am having a problem in echoing the value inserted within author_id field in the list box:
<?php
# display all php errors
error_reporting(-1);
ini_set('display_errors', 1);
# include dbConnection details
require '../includes/dbconn.php';
# initially set $id to empty
$id = null;
# if $id is not empty, GET the id
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
# if $id is empty then send the user back to index.php
if ( null==$id ) {
header("Location: index.php");
exit();
}
if ( !empty($_POST)) {
// keep track validation errors
$joke_textError = null;
$authorError = null;
// keep track post values
$joke_text = $_POST['joke_text'];
$author_id = $_POST['author_id'];
// validate input
$valid = true;
if (empty($joke_text)) {
$joke_textError = 'Please enter joke text';
$valid = false;
}
// update data
if ($valid) {
$sql = "UPDATE joke set joke_text = ?, author_id = ? WHERE id = ?";
$update = $dbConnection->prepare($sql);
$update->execute(array($joke_text,$author_id,$id));
header("Location: index.php");
exit();
}
} else {
$sql = "SELECT joke.id, joke.joke_text, joke.joke_date, author.name, author.email, joke.author_id, author.id
FROM joke INNER JOIN author
ON author_id = author.id
WHERE joke.id = ?";
$select = $dbConnection->prepare($sql);
$select->execute(array($id));
$data = $select->fetch();
$joke_id = $data['id'];
$joke_text = $data['joke_text'];
$joke_date = $data['joke_date'];
$author_name = $data['name'];
$author_email = $data['email'];
$author_id = $data['author_id'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Update Author</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../includes/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<h1>Update Author</h1>
</div>
<form action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php if (!empty($nameError)){ echo 'error';}?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="joke_text" type="text" placeholder="joke text" value="<?php if (!empty($joke_text)){ echo htmlspecialchars(trim($joke_text)); } ?>">
<?php if (!empty($joke_textError)) {
echo '<span class="help-inline">' . $joke_textError . '</span>';
} ?>
</div>
</div>
<select name="author_id" id="author_id">
<option value="">Select one</option>
<?php
$sql2 = 'SELECT id, name FROM author';
foreach ($dbConnection->query($sql2) as $data2) { ?>
<option value="<?php echo $data2['id']; ?>"
<?php if(isset($_POST['author_id']) && $_POST['author_id'] == $data['author_id']) { echo 'selected'; } ?>>
<?php echo htmlspecialchars($data2['name'], ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php } ?>
</select>
<div class="form-actions">
<button type="submit" class="btn btn-green">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</body>
</html>
The data updates into the database just fine, can not figure how to echo it back out into the author_id listbox. If someone could kindly give some assistance it would be great!
In two pages I have there problem. The first problem is before I submitted I get this alert:
(Notice: Undefined index: submit in C:\xampp\htdocs\art-legend\12\admin\add.php on line 15)
and the line 15 in this page is
(if ($_POST['submit'] && !empty($_FILES)){)
The second problem is before I put any image they put that I have an image on the top but I still don't put any image and I have this picture
And the third error is when I upload an image I can't see it and I have a screen like the last screen .
<!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=windows-1256" />
<title>Untitled Document</title>
<title>Untitled Document</title>
</head>
<body>
<?
if ($_POST['submit'] && !empty($_FILES)){
$formok = TRUE;
$title = $_POST['title'];
$thread = $_POST['elm1'];
$date = date("d/m/y h;i:s");
$path = $_FILES['upload']['tmp_name'];
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$type = $_FILES['upload']['type'];
$error = $_FILES['upload']['error'];
if (!is_uploaded_file($path)){
$formok = FALSE;
echo "there is no file uploaded try again";
}
if (!in_array($type,array('image/png','image/jpg','image/jpeg'))){
$formok = FALSE ;
echo "the file is not image try again ";
}
if (filesize($path)>800000){
$formok = FALSE ;
echo "the file is bigger ";
}
if ($formok){
if ($connect = mysqli_connect('localhost','root','adminpass','flip')){
$content = file_get_contents($path);
$safetitle = mysqli_real_escape_string($connect,$title);
$safethread = mysqli_real_escape_string($connect,$thread);
$safeimage = mysqli_real_escape_string($connect,$thread);
$sqltitle ="insert into title(title) values ('$safetitle')";
$sqlthread = "insert into threads (topic,date) values ('$safethread','$date')";
$sqlimge ="insert into images (name,size,type,content) values ('$name','$size','$type','$safeimage')";
$querytitle = mysqli_query($connect,$sqltitle);
$querythread = mysqli_query($connect,$sqlthread);
$queryimage = mysqli_query($connect,$sqlimge);
if ($querytitle && $querythread && $queryimage){
$imageid = mysqli_insert_id($connect);
}
mysqli_close($connect);
}
else {
echo "There is error in database connect";
}
echo "insert done all ";
}
}
?>
<img src="image.php?id=<?=$imageid; ?>" />
<hr />
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" enctype="multipart/form-data">
<p>
title :
<input type="text" name="title" />
</p>
<div>
<textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">
</textarea>
</div>
<input type="hidden" name="MAX_FILE_SIZE" value="800000" />
<p>
<input type="file" name="upload" />
</p>
<p>
<input type="submit" name="submit" value="process" />
</p>
</form>
</body>
</html>
--
<?
$imageid = $_GET['id'];
if ( mysqli_connect('localhost','root','adminpass','flip')){
$escape = mysqli_real_escape_string($connect,$content);
$sql = "select type,content from images where id =$imageid";
$query = mysqli_query($connect, $sql);
$fetch = mysqli_fetch_array($query,MYSQLI_ASSOC);
mysqli_free_result($query);
mysqli_close($connect);
}
else {
echo"ther is no connection 2";
}
if (!empty($fetch)){
header("Content-type:{$fetch['type']}");
echo $fetch['content'];
}
?>
Use isset
isset — Determine if a variable is set and is not NULL
<?
if (isset($_POST['submit']) && !empty($_FILES)){
I am making a quiz in php and I am having trouble advancing to the next question if they get the right answer. I want to stay on the same page. I tried adding 1 to the primary key of the question if a right answer is submitted but that didn't seem to work.
<?php
include('includes/config.inc.php');
?>
<?php
if ($_POST==true && array_key_exists('ans', $_POST)){
$ans = $_POST['ans'];
$question = $_POST['question'];
$sql=mysql_query("SELECT * FROM answer WHERE pk_answer = $ans;");
while($row=mysql_fetch_array($sql)){
$correct=$row['correct'];
}
echo $correct;
if ($correct == 1) {
echo "You are so cool!!!!";
} else {
$msg = "You submitted an incorrect answer. Please try again.";
$incorrect = $ans;
}
}
?>
<!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>G.A.M.E.</title>
<style>
.incorrect {
color: #F00;
font-weight:bold;
}
</style>
</head>
<body>
<h3>ASTM SAFETY QUIZ QUESTION 1</h3>
<?php
$sql=mysql_query("SELECT * FROM quiz LIMIT 1");
while($row=mysql_fetch_array($sql)){
$pk_quiz=$row['pk_quiz'];
$fk_module=$row['fk_module'];
$fk_task=$row['fk_task'];
$quiz_benchmark=$row['quiz_benchmark'];
$question=$row['question'];
?>
<p><?php echo $question; }?></p>
<form id="quiz" name="form1" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<?php $sql2=mysql_query("SELECT * FROM answer ORDER BY RAND()");
while($row2=mysql_fetch_array($sql2)){
$pk_answer=$row2['pk_answer'];
$fk_quiz=$row2['fk_quiz'];
$answer=$row2['answer'];
$correct=$row2['correct'];
?>
<input type="radio" name="ans" value="<? echo $pk_answer; ?>" id="RadioGroup1_0" />
<?php if ($fk_answer = $pk_quiz) {
if ($incorrect == $pk_answer) {
echo '<span class="incorrect">'.$answer."</span>";
} else {
echo $answer;
}
}}?>
<input name="question" type="hidden" value="<?php echo $pk_quiz; ?>" />
<br /><input name="Submit" type="submit" value="submit" />
</p>
</form>
<?php if ($msg == true) { echo $msg; } ?>
</body>
</html>
I am trying to make a survey but when I have an empty record in my msql database he just shows an empty question is there a possibility to skip empty records?
<?php
session_start();
include "config.php";
connDB();
$some_questions = mysql_num_rows(mysql_query("SELECT id FROM question"));
if($_POST['next'] && $_SESSION['qnumber'] != '' && $_POST['question'.$_SESSION['qnumber']] != '')
{
if($_POST['question1']){
$_SESSION['antwoordjes'] = $_POST['question1'];
}else{
$_SESSION['antwoordjes'] .= '|'.$_POST['question'.$_SESSION['qnumber']];
}
$_SESSION['qnumber']++;
$questionnumber = $_SESSION['qnumber']++;
$sql = "SELECT id, question FROM question WHERE id = '$questionnumber'";
$result = mysql_query($sql);
while ($count = mysql_fetch_array($result)){
if($count['question'] == null)
{
$_SESSION['qnumber']++;
}
}
}
if($_POST['question'.$some_questions] != '' && $_SESSION['qnumber'] >= ($some_questions + 1))
{
mysql_query("INSERT INTO answers (ip,answers,datum) VALUES ('".$_SERVER['REMOTE_ADDR']."','".$_SESSION['antwoordjes']."',NOW())");
session_destroy();
header("Location: outro.php");
}
if($_SESSION['qnumber'] == '' || $_SESSION['qnumber'] >= ($some_questions + 1))
{
$quest = 1;
$_SESSION['qnumber'] = $quest;
}
else{
$quest = $_SESSION['qnumber'];
}
$data = mysql_fetch_array(mysql_query("SELECT question,answers FROM question WHERE id='".$quest."'"));
$answers = explode('|',$data['answers']);
$quest = stripslashes($data['question']);
if(empty($_POST['atext']))
{
}else{
$quest = $_POST['hsvraag'];
$commentary = $_POST['atext'];
toevoegenOverig($commentary, $quest);
}
?>
<script type="text/javascript">
function disablefield(){
if (document.getElementById('yes_radio').checked == 1){
document.getElementById('textbox_A').disabled='disabled';
document.getElementById('textbox_A').value='';
}else{
document.getElementById('textbox_A').disabled='';
document.getElementById('textbox_A').value=''; }
}
</script>
<!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>
<!-- <script type="text/javascript" src="abc.js"></script> -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Internet onderzoek</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table align="left">
</table>
<div class="centrum">
<div class="header">Internetsurvey</div>
<div class="content" id="content">
<div class="balk">Introductie | <span style="color:#000033;">question</span> | end</div>
<br/>
<form method="post" action="vragenv.php">
<?php
$nummer = 1;
foreach($answers as $answer)
{
echo '<input id="yes_radio" type="radio" name="question'.$_SESSION['qnumber'].'" value="'.$nummer.'" id="answer'.$nummer.'" onChange="disablefield();"/><label for="answer'.$nummer.'">'.$answer.'</label><br />';
echo '<input type="hidden" name="hsvraag" value="'.$quest.'"/>';
$nummer++;
}
?>
</br>
<br/><input type="text" id="textbox_A" required name="atext"/><br />
<input type="submit" name="next" value="next" class="knop" />
</form>
</div>
</div>
</body>
</html>
Tweak your query.
SELECT
`id`,
`question`
FROM
`question`
WHERE
`id` = '$questionnumber'
AND
`question` IS NOT NULL
AND
LENGTH(TRIM(`question`))>1