I'm using Italy language as main language in my website so when i edit details the some of language characters automatically converting to special character. does anyone know how to fix this issue...!
here is the code which i used to edit database value and convert specialchars
$title7 = mysql_real_escape_string(htmlspecialchars($_POST['title7']));
$description7 = mysql_real_escape_string(htmlspecialchars($_POST['description7']));
Here is the full code which i used to edit database values
// connect to the database
include('db.php');
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$language = mysql_real_escape_string($_POST['txtLanguage']);
$pkg_name = mysql_real_escape_string($_POST['pkg_name']);
$category = mysql_real_escape_string($_POST['category']);
$title = mysql_real_escape_string($_POST['title']);
$description1 = mysql_real_escape_string($_POST['description1']);
$title2 = mysql_real_escape_string($_POST['title2']);
$description2 = mysql_real_escape_string($_POST['description2']);
if ($pkg_name == '' || $category == '')
{
// generate error message
$error = 'ERROR: Please fill in Package name field!';
//error, display form
renderForm($id,$language,$pkg_name,$category,$title,$description1,$title2,$description2);
}
else
{
// save the data to the database
mysql_query("UPDATE saved_packages SET
language ='$language',
pkg_name ='$pkg_name',
category ='$category',
title ='$title',
description1 ='$description1',
title2 ='$title2',
description2 ='$description2',
WHERE id='$id'");
// once saved, redirect back to the view page
header("Location: adm_view_package.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
And here is the result
Don't use htmlspecialchars when save data to database.
You should only do:
$title7 = mysql_real_escape_string($_POST['title7']);
$description7 = mysql_real_escape_string($_POST['description7']);
And when render the data get from database, use it:
echo htmlspecialchars($title7);
echo htmlspecialchars($description7);
Related
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
i have a script that saves records to mysql with no problem. but i want to add some code to show an error message if the name or code already exists in the database. the code is like below;
<?php
$urunadi = $_POST["urunadi"];
$malzemekodu = $_POST["malzemekodu"];
$urunkategorisi = $_POST["urunkategorisi"];
$birim = $_POST["birim"];
$miktar = $_POST["miktar"];
$personel = $_POST["personel"];
$birimfiyat = $_POST["birimfiyat"];
$toplamfiyat = $_POST["birimfiyat"]*$_POST["miktar"];
$fiyatbirimi = $_POST["fiyatbirimi"];
if(empty($urunadi)){
echo("<center><b>Product name empty, please go back and fill this line.</b></center>");
}else
if(empty($miktar)){
echo("<center><b>Product amount empty, please go back and fill this line.
}else
if(empty($malzemekodu)){
echo("<center><b>Product code empty, please go back and fill this line.</b></center>");
}else
if(empty($birimfiyat)){
echo("<center><b>Unit price empty, please go back and fill this line.</b></center>");
}else{
include "database.php";
$sql = (" insert into `depo` (`urunadi`,`malzemekodu`,`urunkategorisi`,`birim`,`miktar`,`personel`,`birimfiyat`,`toplamfiyat`,`fiyatbirimi`)
VALUES ('$urunadi','$malzemekodu','$urunkategorisi','$birim','$miktar','$personel','$birimfiyat','$toplamfiyat','$fiyatbirimi');");
$kayit = mysql_query($sql);
}
if (isset ($kayit)){
echo "<center>Data saved</center>";
}
else {
echo "<center>Data could not be saved</center>";
}
if (isset($_REQUEST["kullanici"])) {
include("database.php");
$sql = ("select * from uye");
}
else {
header ("Location: uyari.html");
}
?>
I have a website, which you press a button and a popup DIV loads up.
On this DIV is a JQuery Validator form which submits to a separate PHP file.
The PHP logins to a database through MySQLi and adds a user. Whilst it does it, at each stage it does an echo message (the idea is that I know what its doing).
This leaves me with a white screen with several lines of information. Its fantastically useful but very ugly from the nice popup div registration.
Is there any way, at the end of the PHP it can redirect to another page assuming there was a blank div in it where the echo information can go, and I can jazz the remaining page up with HTML5 and CSS.
If so how do I get the echo messages into this div?
Thanks
Please see the snippet (which is working) below - but go easy on me as its only been a couple of weeks of learning.
function webmailSignUp($db_connection,$db_con_table) //The function for the website REGISTER FORM
{
$webmailFullName = $_POST['webmailFullName'];
$webmailUserName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if (checkBlankFieldsError($webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$webmailDOB) == false)
{
echo "There are no empty Form Input Fields<br>";
//Connecting to MySQL
if (mysqli_connect_errno($db_connection))
{
echo "Failed to connect to MySQL database:" . mysqli_connect_error();
echo "<br>";
}
else
{
echo "Connected to database<br>";
//Check that there is no existing name in the table
if (checkInField($webmailUserName,$db_connection,$db_con_table,"userName") == false)
{
//Check DOB Field
$dob = $webmailDOB; //or use for non-iso: convertDate($webmailDOB);
echo "DOB is: $dob<br>";
//Binding and Query to prevent SQL injection
$query = "INSERT INTO $db_con_table(userFullName,userName,userExEmail,userPhone,userDOB) VALUES(?,?,?,?,?)";
$requery = $db_connection->prepare($query);
$requery->bind_param("sssss",$webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$dob);
if ($requery->execute())
{
echo "$webmailUserName has been added to the Webmail Database<br>";
}
else
{
echo "bind failed on $webmailUserName <br>";
}
//Close Database
$db_connection->close();
echo "Database is Closed.<br>";
}
else{echo "There is already a user registered with this username. Please try a different one.<br>";}
}
}
else
{
echo "There is 1 or more empty input fields. Please try again.<br>";
}
}
function checkInField($value,$db_connection,$db_con_table, $db_field) // Checks a value is not within a database field
{
$query = "SELECT $db_field FROM $db_con_table WHERE $db_field='$value'";
$result = $db_connection->query($query) or die($mysqli->error());
// GOING THROUGH THE DATA
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "User $value found: '$row[$db_field]' in the table $db_con_table column $db_field<br>";
return true;
}
}
else
{
echo "User $value has not been found in the table $db_con_table column $db_field<br>";
return false;
}
}
function checkBlankFieldsError($field1,$field2,$field3,$field4,$field5) //Checks if form fields are blank
{
$fields = array($field1,$field2,$field3,$field4,$field5);
$error = false;
foreach($fields AS $fieldname) //Loop trough each fieldname in the fields array
{
if(empty($fieldname))
{
$error = true;
}
else
{
}
}
return $error;
}
function convertDate($aString) //Converts a String to a Date in Y-M-D format
{
$date2 = DateTime::createFromFormat('m/d/Y', $aString);
return $date2->format('Y-m-d');
}
//Main Code Sequence on form buttons
if(isset($_POST['webmailRegisterSubmit']))
{
webmailSignUp($mysqli_db,$db_table);
echo "End of Registration.<br>";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
echo "End of Password Reset Request.<br>";
}
If you really want a redirection, you will have to store your messages somewhere. I suggest you to save them in the user session. The workflow would be :
user do action (save form / get page : anything)
server treat the request and store a new "message" in a specific array in the user session (standard php $_SESSION) depending on the situation (error message ? success message ?). At this point you should store the message and its level (INFO/WARNING/ERROR/SUCCESS/etc)
server do a rediction (if needed)
create a method which :
retrieve all store message and delete them directly cause you want to display them only once
display them on your DIV
you're done
The good thing with this worklow is that it will work even without a redirection as you separate clearly messages addition/storing and display.
Hope this helps
i have this code to save note from text area
this is my post-note.php file
<?php
include('connect.php');
if(isset($_POST['note_title'])){
$note_title = $_POST['note_title'];
$note_description = $_POST['note_description'];
$login_user_id = $_SESSION['user_id'];
$errors = array();
if($note_title == ""){
$errors['note_title'] = 'fine';
}else{
$errors['note_title'] = 'fine';
}
if($note_description == ""){
$errors['note_description'] = '<span class="note_description">Please enter something</span>';
}elseif(strlen($note_description) < "3"){
$errors['note_description'] = '<span class="note_description">your note is too short</span>';
}else{
$errors['note_description'] = 'fine';
}
if($errors['note_title'] && $errors['note_description'] == 'fine'){
$Query = "INSERT INTO notes (note_title, login_user_id, note_description, is_private)
VALUE('$note_title', '".$login_user_id."', '".$note_description."','0')";
if (!mysql_query($Query)){
die('Error: ' . mysql_error());
}
$errors['done'] = 'done';
unset($_POST['note_title']);
unset($_POST['note_description']);
}
}
echo json_encode($errors);die;
?>`
i want to insert first time as new row then want to update that row in database
In notes table, add a column id (if its not already there).
On create note page use above code.
On update note page pass id field of that note in $_POST.
So if isset($_POST['id']) write an UPDATE note ... WHERE id=$_POST['id'].
This will update already created note or will insert if its a new note.
filter user inputs before inserting though
can anyone help me with the situation I'm in. I've been trying to find answers on how to display a user's first name, last name email...etc from the table that has the info stored but my only luck with echoing this info is only getting either ALL the info for a certain feel to show like all emails instead of just 1 specific email for the user or I just end up with mysql errors.
here's my index.php source
<?php
session_start();
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$email = $_SESSION['email'];
$firstname = $_SESSION['first_name'];
$lastname = $_SESSION['last_name'];
$businessname = $_SESSION['company_name'];
$country = $_SESSION['country'];
$plan = $_SESSION['plan'];
} else {
header("Location: http://somewebsite.com");
}
include 'connect.php';
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
?>
for instance I would like to echo the user's first name in the header
<span class="username">USER</span> <--replace user with logged in user's firstname n last name-->
You can do something like this:
Write a function to fetch specific data from the table such as one below.
function getuserfield($field) {
$query = "SELECT $field FROM users WHERE id='".$userid."'";
if ($query_run = mysqli_query($query)) {
if ($query_result = mysqli_result($query_run, 0, $field)) {
return $query_result;
}
}
}
/* userid = $_SESSION['id']; */
The "$query_result" will display the username. $field is the specific field you want to display. By this function you can fetch any particular data from the specified field