My form won't submit to the database (PHP/MySQL) - php

I have a form I made using HTML/PHP, And I would like it to submit to the database; I have a movies website and I am currently working on the admin panel, I want it to have a form that adds new movies to the site, I tried out my form, but nothing goes to the database. The connection with the database is fine and the queries look fine to me, I honestly do not know what the problem is.
P.S. I am making it in Arabic, the Arabic writing does not mean anything..
PHP/HTML code:
<?php
session_start();
include('php/config.php');
if($_SESSION['username'] != true){
header('Location: http://www.domain.com/');
}
//this form allows to choose what to do (e.g. add new movie)...
else{
echo'
<head>
<link rel="stylesheet" href="css/main.css" />
<link rel="stylesheet" href="css/admin.css" />
<meta charset="utf-8"/>
<title>Admin Panel v1.0</title>
</head>
<ul class="management-b">
<li>إضافة فيلم جديد</li>
<li>إضافة مسلسل جديد</li>
<li>مسح فيلم/مسلسل</li>
</ul>
';
}
//this form adds new movies...
connectDB();
$genreQuery = mysql_query("SELECT genre FROM Genres");
echo'
<head>
<link rel="stylesheet" href="css/main.css"/>
<link rel="stylesheet" href="css/admin.css"/>
<meta charset="utf-8" />
</head>
<form method="post" id="new-movie">
عنوان الفيلم:<input type="text" class="new-movie-title" name="new-movie-title" /><br/><br/>
وصف الفيلم:<textarea class="new-movie-desc" name="new-movie-desc" cols="50" rows="7"></textarea><br/><br/>
نوع الفيلم:<select class="new-movie-genre" name="new-movie-genre">';
while($options = mysql_fetch_array($genreQuery, MYSQL_ASSOC)){
echo '<option>'.$options["genre"].'</option>';
}
echo'</select><br/><br/>
تاريخ الفيلم:<select class="new-movie-year" name="new-movie-year">';
for($years = 1995; $years<2017; $years++){
echo '<option>'.$years.'</option>';
}
echo'
</select><br/><br/>
رابط الفيلم:<input type="text" name="new-movie-link" class="new-movie-link"/><br/><br/>
صورة الفيلم:<input type="text" name="new-movie-img" class="new-movie-img" /><br/><br/>
تقييم imDB:<input type="text" name="new-movie-imdb" class="new-movie-imdb"/><br/><br/>
<input type="submit" name="new-movie-submit" class="new-movie-submit" value="إضافة الفيلم" />
</form>
';
if(isset($_POST['new-movie-submit'])){
connectDB();
$mNewTitle= $_POST['new-movie-title'];
$mNewDesc= $_POST['new-movie-desc'];
$mNewGenre= $_POST['new-movie-genre'];
$mNewYear= $_POST['new-movie-year'];
$mNewURL= $_POST['new-movie-link'];
$mNewIMG= $_POST['new-movie-img'];
$mNewIMDB= $_POST['new-movie-imdb'];
mysql_query("INSERT INTO Movies(title, description, genre, url, image, imdb, release-year) VALUES('$mNewTitle', '$mNewDesc', '$mNewGenre', '$mNewURL', '$mNewIMG', '$mNewIMDB', '$mNewYear'");
closeDB();
}
?>

If you checked for errors MySQL would tell you that you don't have a column identifier named year as release-year contains a dash in it which makes MySQL think you are subtracting the column identifier year from release. Wrap that column name in ticks to resolve this.
mysql_query("INSERT INTO Movies(title, description, genre, url, image, imdb, `release-year`) VALUES('$mNewTitle', '$mNewDesc', '$mNewGenre', '$mNewURL', '$mNewIMG', '$mNewIMDB', '$mNewYear'");
As mentioned in comments you are using an obsolete API as the mysql_* functions have all been removed from PHP in PHP 7 and you are wide open to SQL injections which is the most common form of web based attacks.
And as I mentioned before, you don't check for or handle errors. You would have caught this error quickly with basic error checking. You also need to be prepared for when errors happen or else your users will have a bad experience when an error occurs.

Related

display user contents with php [duplicate]

This question already has answers here:
php mysql storing line breaks in text area in database
(4 answers)
Closed 3 months ago.
i'm writing simple program that allow user to write their contents and post them
i'm using php ,html,css and mysql database
assume user has written a content in this format
i know codes written in php will allow user to post and store contents in database
i will use <?php echo $row['content']; ?> to display content posted by the user
but contents are not displayed in similary format as it was written by the use in paragraph formats(in format of more than one paragraph),insetad it display like this
Python datatypes.....To get Python handwritten notes, visit the link in the bio.....Visit our site for free project source codes-- copyassignment.com.....Turn on post notifications for more such posts like this.....Follow #python.hub for more content on computer science,
what's the good idea on this problem ? how can i solve it so that contents should be displayed as it is written by the user,,,
any help will be appreciated
<?php
require_once 'dbconfig.php';
if(isset($_POST['btnsave']))
{
$content = $_POST['content'];// user email
$stmt = $DB_con->prepare('INSERT INTO template(content) VALUES(:content)');
$stmt->bindParam(':content',$content);
$stmt->execute();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-4">
<form method="post">
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Description</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="content"></textarea>
</div>
<button type="submit" name="btnsave">ok</button>
</form>
<div>
<div>
<div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
<?php echo nl2br($row['content']); ?>
Use nl2br to convert Input/textarea linebreaks to real html linebreaks (br).

Taking mySQL database input from HTML form with PHP

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

Storing data on multiple pages with PHP

I'm building a business planner based on a blog model. I can't however do it over multiple pages. On page 1, when the user clicks "Next", it's like clicking "Post". The data is stored and added to the list of other business plans, or "posts". One the first page, the data is stored by "Insert"ing it into the database. I thought maybe I could simply "Update" the database on page 2 and so on to eliminate multiple listed "posts" or business plans. The data is being stored from the first page, but not the second page. If I add the data for each page using "INSERT INTO..." that works, but each pages is collected as a separate business plan, or multiple posts. Any advice is appreciated.
Here's Page 1:
<?php
session_start();
include_once("db.php");
if(isset($_POST['post'])) {
$title = strip_tags($_POST['title']);
$compName = strip_tags($_POST['compName']);
$createdBy = strip_tags($_POST['createdBy']);
$phone = strip_tags($_POST['phone']);
$title = mysqli_real_escape_string($db,$title);
$compName = mysqli_real_escape_string($db,$compName);
$createdBy = mysqli_real_escape_string($db,$createdBy);
$phone = mysqli_real_escape_string($db,$phone);
$date = date('l jS \of F Y h:i A');
$sql = "INSERT INTO plans (title, date, compName, createdBy, phone) VALUES('$title', '$date', '$compName', '$createdBy', '$phone')";
mysqli_query($db, $sql);
header("Location: post2.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<div class="container">
<head>
<title>Create Business Plan</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h2>Create a new business plan</h2>
<form action="post1.php" method="post" enctype="multipart/form-data">
<br /><br />
<p>Plan Title: <input name="title" type="text" autofocus size="48"></p>
<p>Company Name: <input name="compName" type="text" autofocus size="48"></p>
<p>Business Type: <input placeholder="Ie. Inc. (USA) or Oy (Finland)" name="bizType" type="text" autofocus size="48"></p>
<p>Created By: <input name="createdBy" type="text" autofocus size="48"></p>
<p>Phone: <input name="phone" type="text" autofocus size="48"></p>
<br /><br />
<form action="<?php 'post2.php=?pid=$id'; ?>">
<input name="post" type="submit" value="Next">
</form>
<br /><br />
</form>
</body>
</div>
</html>
Here's Page 2:
<?php
session_start();
include_once("db.php");
if(isset($_POST['post'])) {
$marketPlan = strip_tags($_POST['marketPlan']);
$economics = strip_tags($_POST['economics']);
$products = strip_tags($_POST['products']);
$customers = strip_tags($_POST['customers']);
$marketPlan = mysqli_real_escape_string($db,$marketPlan);
$economics = mysqli_real_escape_string($db,$economics);
$products = mysqli_real_escape_string($db,$products);
$customers = mysqli_real_escape_string($db,$customers);
$date = date('l jS \of F Y h:i A');
$sql = "UPDATE plans SET marketPlan='$marketPlan', economics='$economics', products='$products', customers='$customers' WHERE id=$pid";
mysqli_query($db, $sql);
header("Location: post3.php"); //CHANGE LOCATION FOR NEXT PAGE
}
?>
<!DOCTYPE html>
<html lang="en">
<div class="container">
<head>
<title>Create Business Plan</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h2>The Marketing Plan</h2>
<form action="post2.php" method="post" enctype="multipart/form-data">
<br /><br />
<h4>Market Research</h4>
<p>The marketing plan requires intensive research for the type of industry your business wants to enter. It is very dangerous to assume that you are already well informed about your intended market. Market research is vital to make sure you are up to date. Use the business planning process as your opportunity to uncover data and to question your marketing efforts.</p>
<textarea name="marketPlan" rows="15" cols="100"></textarea></p><hr />
<h4>Economics</h4>
<p>What is the total size of your market? What percent of market share will you have? (This is important only if you think you will be a major factor in the market.) What is currently in demand in your target market? What are the trends in target market—growth, consumer preferences, and in product development? Growth potential and opportunity for a business of your size.
<textarea name="economics" rows="15" cols="100"></textarea><hr />
<h4>Products</h4>
<p>In the <i>Products and Services</i> section, you described your products and services from your point of view. Now describe them from how your customers see them.</p><br /><textarea name="products" rows="15" cols="100"></textarea></p><hr />
<h4>Customers</h4>
<p>Identify your targeted customers, their characteristics, and their geographical location. This is known as customer demographics.</p>
<textarea name="customers" rows="15" cols="100"></textarea></p>
<input name="post" type="submit" value="Next">
</form>
</body>
</div>
</html>
do some thing like this, rather than inserting and updating the data to database, store the values in session variables, i mean
example :
$_SESSION["title"] = strip_tags($_POST['title']);
store every option in session variable like this until you reach the last page.
finally in the last page
insert it to the db. like this,
insert into table ('title',.....) values ($_SESSION["title"],....);
always use sessions when you want to pass data across multiple pages.
I think you are doing right only. First post have to insert those details in table, next post update what are fields you want to update.
in second page you have to get the id from your url
if (isset($_GET['pid']))
$pid = $_GET['pid'];
as you try to update an id that doesnt is defined
You must pass the ID of the newly created record to the next page; the most secure way is probably to store it in the session. So, on page one, change this:
mysqli_query($db, $sql);
To
$query = mysqli_query($db, $sql);
$_SESSION['new_plan_id'] = $query->insert_id;
Then, in your second page query the ID again
if (isset($_SESSION['new_plan_id']))
{
$pid = $_SESSION['new_plan_id'];
}
else
{
die('No valid session');
}
After a user finished his or her plan, remove the new_plan_id from the session. You may also want to add session_start() to a global include so it is always enabled.

Go to next page after login in PHP [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I'm doing my homework that a webpage.
I created the index page as a login page that have a username input, password input and a login button.
When I click on the button, a php code (it have wroten below) have executed: it uses MySQL for login.
My problem with the login that the redirect. If the typed username and password are okay, the page should go to the next page (for example the next page's link is http://stackoverflow.com).
I use header("location:http://stackoverflow.com"); to go to the next page, but I have got the following error:
Warning: Cannot modify header information - headers already sent by (output started at /users/kzr/www/index.php:60) in /users/kzr/www/index.php on line 14
I've already tried ob_start() with ob_end_flush(), but they didn't changed the situation: the error was same.
Can anybody help me to get work this code?
Note: the PHP and the HTML codes are in once file, but I separated them.
The PHP code:
if(isset($_POST["login"])){
$username=$_POST["username"];
$password=$_POST["password"];
$connect=mysql_connect("127.0.0.1","kzr_zetr","350adagsertesborda");
if($connect){
$db=mysql_select_db("kzr_zetr");
if($db){
$query=mysql_query("SELECT * FROM login WHERE username = '$username' AND password = '$password'");
$rowcount=mysql_num_rows($query);
if($rowcount>0){
$uri="http://kzr.bplaced.de/session/?username=".$username;
header('Location:'.$uri);
print 'sucess';
}else{
echo "<script type='text/javascript'>login_f_val_phperr();</script>";
print 'fail';
}
}
}
}
The HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Bejelentkezés | ZETR</title>
<meta charset="utf-8" />
<meta name="author" content="Kókai Z. Ronald" />
<meta name="contact" content="zr.kokai#gmail.com" />
<meta name="description" content="(Konrad) Zuse Elektronikus Tanulmányi Rendszer" />
<meta name="keywords" content="konrad, zuse, konrad zuse, etr, rendszer, tanulmányi rendszer" />
<meta name="subject" content="Alkalmazott Informatika Házi Feladat Varga István Tanár Úrnak" />
<base href="http://kzr.bplaced.de" />
<link rel="stylesheet" type="text/css" href="/f/font/ubuntu/ubuntu.css" />
<link rel="stylesheet" type="text/css" href="/f/css/zetr.css" />
<link rel="stylesheet" type="text/css" href="/f/css/login.css" />
<link rel="shortcut icon" type="image/x-icon" href="/f/img/favicon.ico" />
<script type="text/javascript" src="/f/script/login-f.js"></script>
</head>
<body>
<div id="container">
<h1>Zuse</h1>
<h2>Elektronikus Tanulmányi Rendszer</h2>
<div id="loginbox">
<form name="login-f" action="" onsubmit="return login_f_val()" method="post">
<input type="text" name="username" id="username" placeholder="Felhasználónév" autocomplete="off" />
<input type="password" name="password" id="password" placeholder="Jelszó" />
<input type="submit" name="login" id="login" value="Bejelentkezés" />
</form>
</div>
</div>
</body>
</html>
Try to put an exit after your header like this :
header(...);exit;
It means on line 60 of index.php something is already causing the headers to be sent; make sure the headers() call is the first thing you do before sending any HTML (or plaintext) output.
headers need to be way above any HTML (even before doctype) and also before echoing ANY html. You will need to do it as high up as possible. And remove PRINT success and fail.

How do I change the value of textarea by option selected?

I am trying to change the contents of depending on the current option selected.
The getData(page) comes back correctly (onChange) but it just doesn't go over to the variable I get "Fatal error: Call to undefined function getData() in C:\xampp\htdocs\pdimi\admin\editpages.php on line 42"
EDIT: This is how I finished it!
Javascript:
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
Select form:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<select name="page" onChange="getData(this)">
<?php
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_POST['page']);
else
$page = '';
$query = "SELECT pageid FROM pages;";
?>
<option value="select">Select Page</option>
<option value="indexpage">Index Page</option>
<option value="starthere">Start Here</option>
</select>
Textarea:
<textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data">
<?php
if (isset($_GET['page'])) {
$sql1 = #mysql_query("SELECT * FROM pages WHERE pageid='".$_GET['page']."'") or die(mysql_error());
$sql2 = #mysql_fetch_array($sql1) or die(mysql_error());
if ($sql1) {
echo $sql2['content'];
}
}
?>
</textarea>
And that is that!
You cannot execute a Javascript function (client side) from PHP (which runs server side).
Also, you need to connect to a database server with user and password, and select a database. Do not use #, it will only prevent you from seeing errors -- but the errors will be there.
In the PHP file you need to check whether you receive a $_POST['page'], and if so, use that as the ID for the SELECT. You have set up a combo named 'page', so on submit the PHP script will receive the selected value into a variable called $_POST['page'].
Usual warnings apply:
mysql_* functions are discouraged, use mysqli or PDO
if you still use mysql_*, sanitize the input (e.g. $id = (int)$_POST['page'] if it is numeric, or mysql_real_escape_string if it is not, as in your case)
If you want to change the content of textarea when the user changes the combo box, that is a work for AJAX (e.g. jQuery):
bind a function to the change event of the combo box
issue a call to a PHP script server side passing the new ID
the PHP script will output only the content, no other HTML
receive the content in the change-function of the combo and verify success
set $('#textarea')'s value to the content
This way you won't have to reload the page at each combo change. Which reminds me of another thing, when you reload the page now, you have to properly set the combo value: and you can exploit this to dynamically generate the combo, also.
Working example
This file expects to be called 'editpages.php'. PHP elaboration is done (almost) separately from data presentation.
<!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 name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PDIMI - The Personal Development and Internet Marketing Institution</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<link href="../style/default.css" rel="stylesheet" type="text/css" media="all" />
<!--[if IE 6]>
<link href="default_ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
</head>
<?php include 'aheader.php';?>
<?php
error_reporting(E_ALL);
if (!mysql_ping())
die ("The MySQL connection is not active.");
mysql_set_charset('utf8');
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_REQUEST['page']);
else
$page = False;
$query = "SELECT pageid, pagename FROM pages;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec)
trigger_error("Cannot fetch data from pages table: " . mysql_error(), E_USER_ERROR);
if (0 == mysql_num_rows($exec))
trigger_error("There are no pages in the 'pages' table. Cannot continue: it would not work. Insert some pageids and retry.",
E_USER_ERROR);
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['pageid'] === $page)
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $page)
$page = $row['pageid'];
$sel = '';
}
$options .= "<option value=\"{$row['pageid']}\" $sel>{$row['pagename']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['page_data']))
{
$page_data = mysql_real_escape_string($_POST['page_data']);
$query = "INSERT INTO pages ( pageid, content ) VALUES ( '{$page}', '{$page_data}' ) ON DUPLICATE KEY UPDATE content=VALUES(content);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
// Anyway, recover its contents (maybe updated)
$query = "SELECT content FROM pages WHERE pageid='{$page}';";
$exec = mysql_query($query);
// who says we found anything? Maybe this id does not even exist.
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textarea = $row['content'];
}
else
$textarea = '';
mysql_free_result($exec);
?>
<body>
<div id="page-wrapper">
<div id="page">
<div id="content2">
<h2>Edit Your Pages Here</h2>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<form name="editpage" method="POST" action="">
<table border="1" width="100%">
<tr>
<td>Please Select The Page You Wish To Edit:</td>
<td>
<select name="page" onChange="getData(this)"><?php print $options; ?></select>
</td>
</tr>
<tr>
<td><textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data"><?php print $textarea; ?></textarea></td>
</tr>
<tr>
<td><input type="Submit" value="Save the page"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
The biggest issue that you have here, is that you need to learn the difference between client side and server side.
Server Side: As the page is loading... We run various code to determine what is going to be displayed and printed into the source code.
Client side: Once the page has loaded... We can then use DOM elements to interact, modify, or enhance the user experience (im making this up as i go along).
In your code, you have a PHP mysql command:
$thisdata = #mysql_query("SELECT * FROM pages WHERE pageid=".getData('value'));
1, Don't use mysql. Use mysqli or PDO
2, You have called a javascript function from your PHP.
There is absolutely no way that you can call a javascript function from PHP. The client side script does not exist and will not run until after the page has stopped loading.
In your case:
You need to server up the HTML and javascript code that you will be using. Once, and only when, the page has loaded, you need to use javascript (client side scripting), to set an event listener to listen for your select change event. Once this event is triggered, then you can determine what you want to do (ie change a textbox value, etc).

Categories