PHP Not supporitng UTF-8? [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 7 years ago.
Hello i have been trying to make { View / edit / add Script }
which i got from google..
but the main issue is it's not supporting arabic language [UTF-8] encode
here is the code:
<?php
ini_set('default_charset', 'UTF-8');
setlocale(LC_ALL, 'UTF-8');
date_default_timezone_set('Asia/Riyadh');
error_reporting(0);
require 'database.php';
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$uidError = null;
$actionError = null;
$reasonError = null;
// keep track post values
$name = utf8_encode($_POST['Name']);
$uid = utf8_encode($_POST['uid']);
$action = utf8_encode($_POST['Action']);
$reason = utf8_encode($_POST['Reason']);
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($uid)) {
$uidError = 'Please enter UID';
$valid = false;
}
if (empty($action)) {
$actionError = 'Please enter action';
$valid = false;
}
if (empty($reason)) {
$reasonError = 'Please enter reason';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO clan187 (name,uid,action,reason) values(?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($name,$uid,$action,$reason,));
Database::disconnect();
header("Location: index.php");
}
}
?>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<br>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="Name" type="text" placeholder="Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($uidError)?'error':'';?>">
<label class="control-label">UID</label>
<div class="controls">
<input name="uid" type="text" placeholder="UUID" value="<?php echo !empty($uid)?$uid:'';?>">
<?php if (!empty($uidError)): ?>
<span class="help-inline"><?php echo $uidError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($actionError)?'error':'';?>">
<label class="control-label">Action</label>
<div class="controls">
<input name="Action" type="text" placeholder="Action" value="<?php echo !empty($action)?$action:'';?>">
<?php if (!empty($actionError)): ?>
<span class="help-inline"><?php echo $actionError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($reasonError)?'error':'';?>">
<label class="control-label">Reason</label>
<div class="controls">
<input name="Reason" type="text" placeholder="Reason" value="<?php echo !empty($reason)?$reason:'';?>">
<?php if (!empty($reasonError)): ?>
<span class="help-inline"><?php echo $reasonError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Well no idea why it's not working for me
any help will be great <3

You haven't said why it doesn't work. You may need to be more verbose.
Unless you specify it, forms are sent in the user's locale encoding. You need to set your form with an encoding. UTF-8 will allow characters from any region/language:
<form class="form-horizontal" action="create.php" method="post" accept-charset="UTF-8">
Now your $_POST[] elements will be already UTF-8 encoded, so you don't need to convert them. Change them to:
$name = $_POST['Name'];
$uid = $_POST['uid'];
$action = $_POST['Action'];
$reason = $_POST['Reason'];

Make sure the following is present in your file:
header('Content-type: text/html; charset=utf-8');
There's also a meta tag for in the document head.
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
Make sure your data source/destination is collated for UTF-8.
Then the only other thing it could be is your text editor encoding. Should be UTF-8 without BOM. No matter what is going on in the file, if the file itself isn't UTF-8 then it won't work.

Related

The text of my web is garbled

I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :

PHP to MYSQL form validation and database insertion with PHP_SELF and php process

I'm trying to use a php form saved on the artistRegister.php below and process it with the file at the bottom named processArtist.php .
I can't find the proper way to populate the fields in case there's an error and when I submit it to the database, I get an empty record on the database.
I'm populating a dropdown list on the navigation bar at header.php and using the same code to connect to the database, so it's not a database communication problem, since I'm able to create new empty records on the submit button press.
Tried several ways to make it work but would appreciate any help debugging the problem at hand.
Thank you advance.
***artistRegister.php***
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php if(isset($title)){ echo $title; }?></title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container-fluid">
<div class="col-xs-3">
</div>
<div class="col-xs-6">
<?php
// define variables and initialize with empty values
$artistName = $artistLabel = $websiteAddress = $facebookAddress = $youtubeAddress ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["artistName"])) {
$nameErr = "Enter Artist name";
}
else {
$artistName = $_POST["artistName"];
}
if (empty($_POST["artistLabel"])) {
$labelErr = "Enter Label name";
}
else {
$artistLabel = $_POST["artistLabel"];
}
}
?>
<form class="form" method="POST" action="processArtist.php">
<div class="form-group">
<label for="artistName">Artist Name:</label>
<input type="text" class="form-control" id="artistName" value="<?php echo htmlspecialchars($artistName);?>">
<span class="error" style="color: red"><?php echo $nameErr;?></span><br>
<label for="artistLabel">Artist Label:</label>
<input type="text" class="form-control" id="artistLabel" value="<?php echo htmlspecialchars($artistLabel);?>">
<span class="error"><?php echo $LabelErr;?></span><br>
<label for="websiteAddress">Artist Website:</label>
<input type="text" class="form-control" id="websiteAddress" value="<?php echo htmlspecialchars($websiteAddress);?>">
<label for="facebookAddress">Artist Facebook:</label>
<input type="text" class="form-control" id="facebookAddress" value="<?php echo htmlspecialchars($facebookAddress);?>">
<label for="youtubeAddress">Artist Youtube:</label>
<input type="text" class="form-control" id="youtubeAddress" value="<?php echo htmlspecialchars($youtubeAddress);?>">
<br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<div class="col-xs-3">
</div>
</div>
</body>
***processArtist.php***
<?php
$host="localhost";
$username="some_user_with_access";
$password="the_user_password";
$db_name="artist_management";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$artistName=$_POST['artistName'];
$artistLabel=$_POST['artistLabel'];
$websiteAddress=$_POST['websiteAddress'];
$facebookAddress=$_POST['facebookAddress'];
$youtubeAddress=$_POST['youtubeAddress'];
$sql="INSERT INTO artists (artistName, artistLabel, websiteAddress, facebookAddress, youtubeAddress)
VALUES
('$artistName', '$artistLabel', '$websiteAddress', '$facebookAddress', '$youtubeAddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

PHP MySQL not updating for CRUD app

I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];

Get an error by changing a post, simple php editing form

All!
I can't change a form I did. It is all functional on my local host (xampp), but when I upload on the server it doesn't work.
I believe the problem is on the query, the login is working so I don't think it's on the database connection or getting the data. I'm getting that $message = "Error"; on the else statement, I also tried to see if the form is working by echo $titulli; echo $content; and it worked.
I user error_reporting(E_ALL & ~E_NOTICE); and got these problems (warnings)
Warning: mysql_real_escape_string(): Access denied for user 'user'#'localhost' (using password: NO) in /home/user/public_html/test/admin-panel.php on line 12
Warning: mysql_real_escape_string(): A link to the server could not be established in /home/user/public_html/test/admin-panel.php on line 12
here is the code:
<?php
session_start();
include_once 'db_connect.php';
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysql_real_escape_string($id);
$titulli = $_POST['emri'.$id];
$titulli1=mysql_real_escape_string($titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysql_real_escape_string($content);
$date = date('Y-m-d H:i:s');
// echo $titulli;
// echo $content;
$update_query = "UPDATE `lagjja`.`content` SET `titulli` = '".$titulli1."', `content` = '".$content1."', `data` = '".$date."' WHERE `content` .`ID` = ".$id1;
$update_result = $mysqli->query($update_query);
if($update_result) {
$message = "you changes succeeded";
}
else {
$message = "Error";
//header('Location: index.php');
//die();
}
}
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
}
else {
echo "Your are not connected return to homepage";
header('refresh:2; url=index.php') ;
die();
}
?>
<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta charset="UTF-8" />
<?php include("head.php"); ?>
<link rel="stylesheet" type="text/css" href="css/style-adminpanel.css" />
<title>Admin-panel</title>
</head>
<body>
<header>
logout
return to page
<div id="logo-postimit">
<img src="img/logo.png" alt="logo" />
</div>
</header>
<?php if(isset($message) && !empty($message) ) {
echo $message
;} ?>
<div id="content">
<div id="krejt-forma">
<?php
$post_query = "SELECT * FROM content LIMIT 3";
$result = $mysqli->query($post_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) : ?>
<!-- 2.1 tab section -->
<div class="forma col-lg-4 col-md-4 col-sm-12">
<form id="post-forma" role="form" name="post-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?update=<?php echo $row['ID']; ?>">
<input class=" form-control titulli col-lg-12 col-md-12 col-sm-12 col-xs-12" type="text" id="emri<?php echo $row['ID']; ?>" name="emri<?php echo $row['ID']; ?>" placeholder="Titulli" value="<?php echo $row['titulli']; ?>" />
<textarea class="form-control mesazhi col-lg-12 col-md-12 col-sm-12 col-xs-12" rows="12" id="mesazhi<?php echo $row['ID']; ?>" name="mesazhi<?php echo $row['ID']; ?>" placeholder="Mesazhi"><?php echo $row['content']; ?></textarea>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
</form>
</div>
<?php endwhile; } ?>
</div>
</div>
<!-- 3.0 footer -->
<footer>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- bootstrap implimentation -->
<script src="js/bootstrap.min.js"></script>
<!-- bootstrap imp end -->
<script src="js/navbar.js"></script>
</footer>
</body>
</html>
here is my db_conncet.php
<?php
/* Konfigurimi i databazes */
define("HOST", "localhost");
define("USER", "laxhja");
define("PASSWORD", "password");
define("DATABASE", "laxhja");
define("SECURE", FALSE);
/* Lidhja me databaze */
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$mysqli->set_charset("utf8");
?>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
change this to
<input type="submit" name="update" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"/>
I solved it by changing the mysql_real_escape_string to mysqli_real_escape_string gave it 2 parameters and its done.
like this.
$con = mysqli_connect("localhost", "laxhja", "password", "laxhja");
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysqli_real_escape_string($con, $id);
$titulli = $_POST['emri'.$id];
$titulli1=mysqli_real_escape_string($con, $titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysqli_real_escape_string($con, $content);
$date = date('Y-m-d H:i:s');...

Updation not working using pdo in php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Categories