Why doesn't my UPDATE query work? MySQL - php

I'm working on a blog website and i'm currently stuck at making a blog edit page. For some reason my blog UPDATE query doesn't work, and i can't figure out why it isn't working. I'm not getting an error. It is just not updating anything.
I'm collecting the data from an old blog and inserting it into my form. And then I'm trying to update it using my update query.
This is my code so far:
aanpassen.php
<?php
$error=false;
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if ( isset( $_POST ['id'], $_POST['title'], $_POST['content'] ) ) {
$id = $_POST ['id'];
$title = $_POST['title'];
$content = nl2br( $_POST['content'] );
if (empty($title) || empty($content) || empty($id)){
$error='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = :title,
article_content = :content WHERE id=:id");
if( $query ){
$id = $_POST ['id'];
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
} else {
exit('bad foo - unable to prepare sql query');
}
}
}
if ( isset( $_GET['id'] ) ) {
$id = $_GET['id'];
$data = $article->fetch_data( $id );
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="title" class="titleform" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea name="content" id="summernote" rows="15" cols="50"><?php echo $data['article_content'] ?></textarea>
<input type="submit" class="buttonclass" value="Aanmaken" />
</form>
<?php
if ($error)
printf('<h1>%s</h1>', $error);
?>
connection.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=cms', 'root', 'root');
} catch (PDOException $e) {
exit('Database error.');
}
?>

you missed ":" in all the bindValue arguments. should be like this:
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
and also if (empty($title) or empty($content) or empty($id)) this should be if (empty($title) || empty($content) || empty($id)) like this

When you access aanpassen.php initially it's in this format right - aanpassen.php?id=1??
Otherwise your code seems fine when I tested it.
Just Change:
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
To:
$success = $query->execute();
header( 'Location: index.php?status='.( $success ? 'ok' : 'failed' ) );exit();

Related

Session will not show new values

I have been trying to get my session update, I have created a basic update with mysql as well, it updates in the sql database but it will not show the change within the page.
I'm not sure what else to check, because I checked within the chrome settings and it does show a php session id value but if I go into session storage it shows nothing.
transaction.php
<?php
$_title = 'Update profile';
require_once(__DIR__.'../../components/header.php');
session_start();
if(! isset($_SESSION['user_name'])){
header('Location: ../sign_in/sign_in.php');
die();
}
if (!isset($_SESSION["lang"])) { $_SESSION["lang"] = "en"; }
if (isset($_POST["lang"])) { $_SESSION["lang"] = $_POST["lang"]; }
require_once(__DIR__.'../../globals.php');
require_once(__DIR__.'../../db.php');
try{
$db = _db();
}catch(Exception $ex){
_res(500, ['info'=>'System under maintainance','error'=>__LINE__]);
}
$userProduct = $_SESSION['user']['user_id'];
$q = $db->prepare('SELECT * FROM users WHERE user_id = :userID');
$q->bindValue(":userID", $userProduct);
$q->execute();
require "../lan/lang." . $_SESSION["lang"] . ".php";
?>
<form class="style_form" id="update_profile" onsubmit="return false">
<div>
<label for="name"><?=$_TXT[63]?></label>
<input type="text" name="name" value="<?php echo $_SESSION['user']['user_name']?>">
</div>
<div>
<label for="last_name"><?=$_TXT[64]?></label>
<input type="text" name="last_name" value="<?php echo $_SESSION['user']['lastName']?>">
</div>
<div>
<label for="email"><?=$_TXT[65]?></label>
<input name="email" value="<?php echo $_SESSION['user']['email']?>" type="text">
<input type="hidden" name="userId" value="<?php echo $_SESSION['user']['user_id'] ?>">
<button onclick="update()" id="updateButton"><?=$_TXT[60]?></button>
</form>
</section>
<?php
require_once(__DIR__.'../../components/footer.php');
?>
api-transaction.php
<?php
require_once(__DIR__.'../../globals.php');
// Validate name
if( ! isset( $_POST['name'] ) ){ _res(400,['name is required']); }
if( strlen( $_POST['name'] ) < _FRIST_NAME_MIN_LEN ){ _res(400,['name min '._FRIST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['name'] ) > _FRIST_NAME_MAX_LEN ){ _res(400,['name max '._FRIST_NAME_MAX_LEN.' characters']); }
// Validate last_name
if( ! isset( $_POST['last_name'] ) ){ _res(400,['last_name is required']); }
if( strlen( $_POST['last_name'] ) < _LAST_NAME_MIN_LEN ){ _res(400,['last_name min '._LAST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['last_name'] ) > _LAST_NAME_MAX_LEN ){ _res(400,['last_name max '._LAST_NAME_MAX_LEN.' characters']); }
// Validate email
if( ! isset( $_POST['email'] ) ){ _res(400,['email is required']); }
if( ! filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL ) ){ _res(400,['email is invalid']); }
$db = require_once(__DIR__.'../../db.php');
try{
session_start();
// $userid = $_SESSION['userId'];
// $userid = $_SESSION['user']['user_id'];
$userid = $_POST['userId'];
$db->beginTransaction();
//Change name
$q = $db->prepare('UPDATE users SET user_name = :update_Name WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_Name', $_POST['name']);
$q->execute();
//Change last name
$q = $db->prepare('UPDATE users SET lastName = :update_lastName WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_lastName', $_POST['last_name']);
$q->execute();
//change email
$q = $db->prepare('UPDATE users SET email = :update_email WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_email', $_POST['email']);
$q->execute();
// change phone number
$q = $db->prepare('UPDATE users SET phone_number = :update_phone WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_phone', $_POST['phone_number']);
$q->execute();
$db->commit();
header('Content-Type: application/json');
$response = ["info" => "info has been updated"];
echo json_encode($response);
}catch(Exception $ex){
http_response_code(500);
echo $ex;
echo 'System under maintainance';
exit();
}

PHP mysql loginreturns Email not found error even though it's in the database

I get this error when i try to login
however the login email and password is already in the MySql database and they have been entered correctly. I am trying to make a website to calculate the odds of winning different types of gambling games and I am going to store the data on the database for each individual user so that they can view it later.
Thanks
login.php
<?php
include('header.html');
if (isset($errors)&& !empty($errors))
{
echo ' <p id="err_msg">Oops! there was a problem:<br>';
foreach ($errors as $msg )
{
echo " - $msg <br>";
}
echo 'Please try again or register here</p>';
}
?>
<form action="login_action.php" method="POST">
<dl>
<dt>Email : <input type="text" name="email"><dd>
<dt>Password: <input type="password" name="pass"><dd>
</dl>
<button type="submit">Login</button>
</form>
register.php
<?php
$page_title = 'GambCalc - Register';
include('header.html');
if ( $_SERVER['REQUEST_METHOD']=='POST')
{
require ('db_connection.php');
$errors = array();
if (empty($_POST['email']))
{$errors[] = 'Enter your first name.' ; }
else
{$e = mysqli_real_escape_string($dbc,trim($_POST['email']));}
if (empty($_POST['pass']))
{$errors[] = 'Enter your password.' ; }
else
{$p = mysqli_real_escape_string($dbc,trim($_POST['pass']));}
if (empty($errors))
{
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query($dbc,$q);
if (mysqli_num_rows($r) != 0)
$errors[] = 'Email address already registered. Login';
}
if (empty($errors))
{
$q = "INSERT INTO users (email, pass) VALUES ('$e',SHA1('$p'))";
$r = mysqli_query($dbc,$q);
if($r)
{
echo '<h1>Registered!</h1>
<p>Login</p>';
}
mysqli_close($dbc);
exit();
}
else
{
echo '<h1>Error!</h1>
<p id="err_msg">The folloiwng error(s) occurred:<br>';
foreach($errors as $msg )
{
echo " - $msg<br>";
}
echo 'Please try again </p>';
mysqli_close($dbc);
}
}
?>
<h1>Register</h1>
<form action="register.php" method="POST">
<p>
Email address : <input type="text" name="email"
value="<?php if ( isset($_POST['email']))
echo $_POST['email'];?>">
</p>
<p>Password : <input type="password" name="pass" value="<?php if(isset($_POST['pass'])) echo $_POST['pass'];?>"></p>
<p><input type="submit" value="Register"></p>
</form>
login_tools.php
<?php # LOGIN HELPER FUNCTIONS.
# Function to load specified or default URL.
function load( $page = 'login.php' )
{
# Begin URL with protocol, domain, and current directory.
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'PHP_SELF' ] ) ;
# Remove trailing slashes then append page name to URL.
$url = rtrim( $url, '/\\' ) ;
$url .= '/' . $page ;
# Execute redirect then quit.
header( "Location: $url" ) ;
exit() ;
}
# Function to check email address and password.
function validate( $dbc, $email = '', $pwd = '')
{
# Initialize errors array.
$errors = array() ;
# Check email field.
if ( empty( $email ) )
{ $errors[] = 'Enter your email address.' ; }
else { $e = mysqli_real_escape_string( $dbc, trim( $email ) ) ; }
# Check password field.
if ( empty( $pwd ) )
{ $errors[] = 'Enter your password.' ; }
else { $p = mysqli_real_escape_string( $dbc, trim( $pwd ) ) ; }
# On success retrieve user_id, first_name, and last name from 'users' database.
if ( empty( $errors ) )
{
$q = "SELECT user_id FROM users WHERE email='$e' AND pass=SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array ( $r, MYSQLI_ASSOC ) ;
return array( true, $row ) ;
}
# Or on failure set error message.
else { $errors[] = 'Email address and password not found.' ; }
}
# On failure retrieve error message/s.
return array( false, $errors ) ;
}
login_action.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
require ( 'db_connection.php' ) ;
require ( 'login_tools.php' ) ;
list ( $check, $data ) = validate ( $dbc, $_POST[ 'email' ], $_POST[ 'pass' ] ) ;
if ( $check )
{
session_start();
$_SESSION[ 'user_id' ] = $data[ 'user_id' ] ;
load('home.php');
}
else { $errors = $data; }
mysqli_close( $dbc ) ;
}
include ( 'login.php' ) ;
?>
Because in your query, it filtered the email with '$e' values. I think you should change it into something like this...
$q = "SELECT user_id FROM users WHERE email='".$e."'";
for checking, you can use var_dump or print_r
You should also update your other queries with the same format.
$q = "INSERT INTO users (email, pass) VALUES ('".$e."',SHA1('".$p."'))";
Change your query to $q = "SELECT user_id FROM users WHERE email='".$e."'";

Why every time f5(refresh) is my website insert data to the database

I have a form that inserts data into the database using mysql. When I click submit (add data) the data is inserted into the database successfully. However, when I press f5 (refresh), the data is still inserted into the database. I do not know where I'm wrong. Please help me. This is my code:
<?php
$username = "user_tintuc"; // Khai báo username
$password = "123456"; // Khai báo password
$server = "localhost"; // Khai báo server
$dbname = "tintuc"; // Khai báo database
// Kết nối database tintuc
$connect = new mysqli($server, $username, $password, $dbname);
//Nếu kết nối bị lỗi thì xuất báo lỗi và thoát.
if ($connect->connect_error) {
die("Không kết nối :" . $conn->connect_error);
exit();
}
//Khai báo giá trị ban đầu, nếu không có thì khi chưa submit câu lệnh insert sẽ báo lỗi
$title = "";
$date = "";
$description = "";
$content = "";
//Lấy giá trị POST từ form vừa submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["title"])) { $title = $_POST['title']; }
if(isset($_POST["date"])) { $date = $_POST['date']; }
if(isset($_POST["description"])) { $description = $_POST['description']; }
if(isset($_POST["content"])) { $content = $_POST['content']; }
//Code xử lý, insert dữ liệu vào table
$sql = "INSERT INTO tin_xahoi (title, date, description, content)
VALUES ('$title', '$date', '$description', '$content')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//Đóng database
$connect->close();
?>
<form action="" method="post">
<table>
<tr>
<th>Tiêu đề:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô tả:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>Nội dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">Gửi</button>
</form>
I edited it like this. But it's still like that.
if (isset($_POST['submit'])){
if(isset($_POST["date"])) { $date = $_POST['date'];}
if(isset($_POST["MAB"])) { $MAB = $_POST['MAB']; }
if(isset($_POST["MBA"])) { $MBA = $_POST['MBA']; }
if(isset($_POST["PAB"])) { $PAB = $_POST['PAB']; }
if(isset($_POST["PBA"])) { $PBA = $_POST['PBA']; }
$sql = "INSERT INTO `dbsht` (`date`, `MAB`, `MBA`, `PAB`, `PBA`) VALUES ('$date', '$MAB', '$MBA', '$PAB', '$PBA')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
This is normal issues. You should use POST-Redirect-GET pattern to prevent it. After insert database successful, you should response with redirect to GET request.
You may try
if ($connect->query($sql) === TRUE) {
$_SESSION["ADD_SUCCESS"] = 1;
header('Location: '.$_SERVER['REQUEST_URI']);
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
For successful message
//Đóng database
$connect->close();
if(isset($_SESSION["ADD_SUCCESS"]))
{
echo "Chúc mừng bạn đã thêm dữ liệu thành công";
unset($_SESSION["ADD_SUCCESS"]);
}
You can fix it, but don't, reorganize it and rewrite it because your approach is border-line terrible.
Have myform.html as one file, your php code for inserting data in db as another file like db_insert.php and your data for db connection (user, pass, db, host) in separate file OUTSIDE of public folder (outside public_html or whatever) in file config.inc.php, for example. Do this and you'll avoid this problem that you have right now and many others.
So in myform.html enter data and submit => db_insert.php gets data from myform.html, fetches data from config.inc.php, enters it in DB and redirects back to myform.html or some other part of your application.
After you make it work and figure it out how and why, then read a few articles about AJAX and how to do the same job without leaving your form page. It's obvious that you just started learning, so make sure you learn it the right way ;)
Once the POST request has been sent the php code should do the necessary logic tests and sanitation routines on the data, construct and execute the sql and finally redirect to either the same page or another. The redirect will prevent the form being re-submitted when refreshing the page
<?php
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
$username = "user_tintuc";
$password = "123456";
$server = "localhost";
$dbname = "tintuc";
$connect = new mysqli( $server, $username, $password, $dbname );
$title = isset( $_POST["title"] ) ? $_POST["title"] : false;
$date = isset( $_POST["date"] ) ? $_POST["date"] : false;
$description = isset( $_POST["description"] ) ? $_POST["description"] : false;
$content = isset( $_POST["content"] ) ? $_POST["content"] : false;
if( $title && $date && $description && $content ){
$sql = 'insert into `tin_xahoi` ( `title`, `date`, `description`, `content`) values (?,?,?,?)';
$stmt=$connect->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssss',$title,$date,$description,$content);
$result=$stmt->execute();
$stmt->close();
/* set a temporary session variable - used to display message */
$_SESSION['dbstatus']=$result ? 'Record added' : 'Sorry - an error occurred';
header('Location: ?status=' . ( $result ? 'ok' : 'error' ) );
} else {
throw new Exception('Failed to prepare sql');
}
} else {
throw new Exception('one or more variables are empty');
}
}catch( Exception $e ){
$message=sprintf('<p>%s</p>',$e->getMessage());
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<th>Tiêu d?:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô t?:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>N?i dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">G?i</button>
<?php
/* Display the message from session variable and unset the variable */
if( !empty( $_GET['status'] ) && isset( $_SESSION['dbstatus'] ) ) {
$message=$_SESSION['dbstatus'];
unset( $_SESSION['dbstatus'] );
}
/* Display whatever is in $message */
echo $message;
?>
</form>
</body>
</html>

SQL Database password protected submission

How do I make the following database only submit the entries if the password matches '1996' - I have tried looking into this and can't find out anything. The following could also have a display.php file that has the database details on and they also have the correct pin coding. I just don't know how to make this part of the coding make sure the pin is correct before submitting the details and if the pin is incorrect then an error message apears.
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $db;
var $pin;
public function display_public() {
$q = "SELECT * FROM sianDB4 ORDER BY created DESC LIMIT 4";
$r = mysql_query($q);
$entry_display = '';
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$title = ($a['title']);
$bodytext = ($a['bodytext']);
$author = ($a['author']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$title
</h2>
<h3>
$bodytext
</h3>
<p>
$author
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="title">Title:</label><br />
<input name="title" id="title" type="text" maxlength="150" />
<div class="clear"></div>
<label for="bodytext">Body Text:</label><br />
<textarea name="bodytext" id="bodytext"></textarea>
<div class="clear"></div>
<label for="author">Author:</label><br />
<textarea name="author" id="author"></textarea>
<div class="clear"></div>
<label for="pin">Pin:</label><br />
<input name="pin" id="pin" type="Password" maxlength="4" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['title'] )
$title = mysql_real_escape_string($_POST['title']);
if ( $_POST['bodytext'])
$bodytext = mysql_real_escape_string($_POST['bodytext']);
if ( $_POST['author'])
$author = mysql_real_escape_string($_POST['author']);
if ( $title && $bodytext && $author ) {
$created = time();
$sql = "INSERT INTO sianDB4
VALUES( '$title','$bodytext','$author','$created')";
return mysql_query($sql);
}else{
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password,$this->pin) or die("Could not connect. " . mysql_error());
mysql_select_db($this->db) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS sianDB4 (
title VARCHAR(150),
bodytext TEXT,
author TEXT,
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
As noted by #Jay, the use of the mysql_* suite of functions is not to be recommended anymore so hopefully you can make use of the code below which uses mysqli instead.
I'm not sure how you were using or presenting the class to the user but you'll no doubt be able to make the necessary changes.
<?php
class simplecms{
/*
Pass in the dbconn as a parameter to this class's constructor
*/
private $db;
private $pin;
public function __construct( dbconn $db=null, $pin=false ){
$this->db=$db;
$this->pin=intval( $pin );
}
public function display_public() {
$sql='select * from `siandb4` order by `created` desc limit 4';
$res=$this->db->query( $sql );
/* use an array rather than concatenating a string for output */
$html=array();
if( $res ){
while( $rs = $res->fetch_object() ){
$html[]="
<div class='post'>
<h2>{$rs->title}</h2>
<h3>{$rs->bodytext}</h3>
<p>{$rs->author}</p>
</div>";
}
} else {
$html[]="
<h2>This Page Is Under Construction</h2>
<p>No entries have been made on this page. Please check back soon, or click the link below to add an entry!</p>";
}
/* hide this from ordinary users somehow */
$html[]="
<p class='admin_link'>
<a href='{$_SERVER['SCRIPT_NAME']}?admin=1'>Add a New Entry</a>
</p>";
/* Add the admin form */
$html[]=$this->display_admin();
/* display stuff */
echo implode( PHP_EOL, $html );
}
public function display_admin() {
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){/* Add record to the db if the pin matches */
$message=$this->write() ? 'Database has been updated' : 'Sorry, unable to add that record - check your PIN is correct';
}
$admin = isset( $_GET['admin'] ) ? intval( filter_input( INPUT_GET, 'admin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
return $admin ? "
<style>
form#admin, form#admin *{display:block;box-sizing:content-box!important;}
form#admin{ width:50%;display:block;clear:both;float:none;margin:0 auto;}
form#admin label{width:100%;clear:both;float:none;margin:0.5rem auto 3rem auto;padding:0.25rem;}
form#admin label input, form#admin textarea{float:right;width:60%;padding:1rem;}
form#span{color:red;}
</style>
<form id='admin' method='post'>
<label for='title'>Title:<input name='title' id='title' type='text' maxlength='150' /></label>
<label for='bodytext'>Body Text:<textarea name='bodytext' id='bodytext'></textarea></label>
<label for='author'>Author:<textarea name='author' id='author'></textarea></label>
<label for='pin'>Pin:<input name='pin' id='pin' type='Password' maxlength='4' /></label>
<input type='submit' value='Create This Entry!' />
<span>{$message}</span>
</form>" : "";
}
public function write(){
$pin = isset( $_POST['pin'] ) ? intval( filter_input( INPUT_POST, 'pin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
$title = isset( $_POST['title'] ) ? filter_input( INPUT_POST, 'title', FILTER_SANITIZE_STRING ) : false;
$bodytext = isset( $_POST['bodytext'] ) ? filter_input( INPUT_POST, 'bodytext', FILTER_SANITIZE_STRING ) : false;
$author = isset( $_POST['author'] ) ? filter_input( INPUT_POST, 'author', FILTER_SANITIZE_STRING ) : false;
if ( $title && $bodytext && $author && $pin===$this->pin ) {
/* ? not sure you really want to run this each and every time but... */
$this->buildtbl();
/* Prepare the sql and execute - return status */
$sql='insert into `sianDB4` set `title`=?, `bodytext`=?, `author`=?;';
$stmt=$this->db->prepare( $sql );
$stmt->bind_param( 'sss', $title, $bodytext, $author );
return $stmt->execute();
}
return false;
}
private function buildtbl(){/* build the table - slightly modified */
$sql='create table if not exists `siandb4` (
`id` int(10) unsigned not null auto_increment,
`title` varchar(150) null default null,
`bodytext` text null,
`author` text null,
`created` timestamp null default current_timestamp,
primary key (`id`)
)engine=innodb;';
$this->db->query( $sql );
}
}//end class
class dbconn{
/* Simple mysqli db connection */
private $conn;
public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
$this->conn=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
}
public function query( $sql ){
return $this->conn->query( $sql );
}
public function prepare( $sql ){
return $this->conn->prepare( $sql );
}
}//end class
?>
<html>
<head>
<title>Simple CMS - Hello Kitty Example!</title>
<style>
h2,h3{font-size:1rem;}
div.post{font-size:0.85rem;border-bottom:1px dotted gray;margin:0 auto 3rem auto;}
</style>
</head>
<body>
<h1>Simple CMS - Hello Kitty Example!</h1>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxxxxx';
$dbname = 'xxxxxx';
$db=new dbconn( $dbhost, $dbuser, $dbpwd, $dbname );
$cms=new simplecms( $db, 1996 );
$cms->display_public();
$db=$cms=null;
?>
</body>
</html>

Update mysql database and skip empty fields

I have two pages, edit.php and editdone.php.
On the edit.php I am able to fill information, which is being sent to editdone.php. That page is then running a query that updates data in the mysql database.
The problem is; if I leave an input field on edit.php empty, editdone.php will then replace the current information in the database with empty data(nothing).
What I want to do is to make the editdone.php update data if something was written in the fields of edit.php. So if I choose to leave some fields empty and for example only fill one field in the form, I want to only update the filled fields with the filled data and NOT replace the not filled field with empty data. Those field should then, if I haven't filled any data in edit.php, keep the already existing data.
edit.php
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
$cn = $_POST['cname'];
?>
<form action="editdone.php" method="POST" enctype="multipart/form-data" name="editdone" onsubmit="return validateForm()">
<input type="hidden" name="namec" value="<?php echo htmlspecialchars($cn); ?>">
<br>
Fyll i Företagets namn: <br>
<input type="text" name="company_name" id="company_name">
<br><br>
Lägg till en logga:
<input type="file" name="image" id="image">
<br><br>
Description:<br>
<textarea name="description" id="description" rows="4" cols="50"></textarea>
<br>
<br>
Fyll i välkomnings meddelande:<br>
<textarea name="welcome_text" id="welcome_text" rows="5" cols="50"></textarea>
<br>
<br>
Fyll i ett tack meddelande:<br>
<textarea name="thanks_message" id="thanks_message" rows="5" cols="50"></textarea>
<br>
<br>
<input type="submit" name="submit" value="Nästa" />
</form>
editdone.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "UPDATE project SET project_name='$company_name', description='$description', image='$image', image_type='$image_type', welcome_text='$welcome_text', thanks_message='$thanks_message' WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
?>
For every input/textarea in edit.php, insert a <input type="hidden" value="company_name_old> etc... with the previous value. Then in editdone.php, check if the value in POST is empty or not.
<?php
$company_name = $_POST['company_name'];
if($company_name==""){
$company_name=$_POST['company_name_old'];
}
...
?>
1 cheap "hack" is to assign the current value of the field to the value of the input field and then concat the two strings or values together then save that var. to the database.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = "";
$description = "";
$welcome_text = "";
$thanks_message = "";
$image = "";
$logo = "";
$image_type = "";
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
if( isset($_FILES) )
{
if( !empty($_FILES) )
{
if( isset($_FILES['image']['tmp_name']) )
{
if( $_FILES['image']['tmp_name'] != "" && !empty($_FILES['image']['tmp_name']) )
{
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
if( $image != "" && !empty($image) )
{
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
}
}
}
}
}
$update_values = array();
if($company_name != "")
$update_values[] = "project_name='".$company_name."'";
if($description != "")
$update_values[] = "description='".$description."'";
if($image != "")
$update_values[] = "image='".$image."'";
if($image_type != "")
$update_values[] = "image_type='".$image_type."'";
if($welcome_text != "")
$update_values[] = "welcome_text='".$welcome_text."'";
if($thanks_message != "")
$update_values[] = "thanks_message='".$thanks_message."'";
$update_values_imploded = implode(', ', $update_values);
if( !empty($update_values) )
{
$q = "UPDATE project SET $update_values_imploded WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
}
?>
Try replacing your query like this.
$q = "UPDATE project SET ";
$q .= $company_name ? "project_name='$company_name', " : "";
$q .= $description ? "description='$description', " : "";
$q .= $image ? "image='$image'," : "";
... so on(all fields)
$q .= "WHERE project_name='$namenamec'";
Make sure you remove , for last value
you can do like this here i have made only one variable you can check for each posted variable and append the $q variable as on
$q = "UPDATE project SET";
if(isset($_POST['namec']) && $_POST['namec']!=""){
$q.=" project_name='".$_POST['namec']."' ,";
}
$q=rtrim(',',$q);
$q.="WHERE project_name=".$namenamec;

Categories