Issue with PHP MySQL and insert into UTF-8 - php

I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
$host = "localhost"; // your mysql server address
$user = "z*******"; // your mysql username
$pass = "m********"; // your mysql password
$tablename = "z*******"; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>

add this line:
mysql_query("SET NAMES 'utf8'");
Like this
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
else{
mysql_query("SET NAMES 'utf8'");
}
Also:
- Add meta charset to the form page
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
or HTML5
<meta charset='utf-8'>

Related

php script using sessions formatting and redirecting to 500

I am new to php and working on a hangman game. I have a home.php that takes you to the homepage and their is a login form that the user must submit a username and a password. If the username and password match with the one I have set, it will redirect to hangman.php. I want some advice if the way I have written the script is correct or not. Also, I am getting a 500 error after the user logs in. I don't know why. I will paste the code down below.
Update: I have added the code for hangman.php
home.php
<?php
// starting a new session
session_start();
if(isset($_POST['uname'], $_POST['psw'])){
$uname= "my_admin";
$psw = "password";
if($_POST['uname'] == $uname && $_POST['psw'] == $psw) {
$_SESSION["uname"] = "my_admin";
$_SESSION["psw"] = "password";
# array holds errors
$errors = array();
# validation starts here
if(empty($_POST['uname'])){
$errors['uname1'] = "Your name cannot be empty";
}
# check strlength
if(strlen($_POST['uname']) < 6){
$errors['uname2'] = "Must be longer than 6 characters";
}
# check username
if ($_POST['uname'] !== "my_admin"){
$errors['uname3'] = "You are not the admin";
}
if($_POST['uname'] == "my_admin" && $_POST['psw'] == "password"){
header('Location:hangman.php');
exit();
}else{
$errors['uname4'] = "Please try again";
}
if(empty($_POST['psw'])){
$errors['psw1'] = "Your password cannot be empty";
}
if(strlen($_POST['psw']) < 6){
$errors['psw2'] = "Must be longer than 6 characters";
}
if($_POST['psw'] !== "password"){
$errors['ps3'] = "AH AH AH thats not it";
}else{
header('Location:hangman.php');
exit();
}
if(count($errors) == 0){
# redirect to the game page
header('Location:hangman.php');
exit();
}
}
}
?>
form for my script to run against
<div class="container">
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname">
<p>
<?php if(isset($errors['uname1']))
echo $errors['uname1']; ?>
</p>
<p>
<?php if(isset($errors['uname2']))
echo $errors['uname2']; ?>
</p>
<p>
<?php if(isset($errors['uname3']))
echo $errors['uname3']; ?>
</p>
<p>
<?php if(isset($errors['uname4']))
echo $errors['uname4']; ?>
</p>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw">
<p>
<?php if(isset($errors['psw1'])) echo $errors['psw1']; ?>
</p>
<p>
<?php if(isset($errors['psw2'])) echo $errors['psw2']; ?>
</p>
<?php if(isset($errors['psw3'])) echo $errors['psw3']; ?>
</p>
<button name="check" type="submit" value="submit">Login</button>
</div>
</form>
hangman.php
<?php
require_once 'hangedman.php';
$words = array('VIETNAM', 'PEOPLE', 'PYTHON');
$numwords = 0;
function printPage($image, $guesstemplate, $which, $guessed, $wrong) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="home.css">
</head>
</html>
<body>
<h1 style='color: red'>Hangman Game</h1>
<br />
<pre style='color: red'>$image</pre>
<br />
<p style='color:red'><strong>Word to guess: $guesstemplate</strong></p>
<p style='color:red'>Letters used in guesses so far: $guessed</p>
<form method="post" action="$script">
<input type="hidden" name="wrong" value="$wrong" />
<input type="hidden" name="lettersguessed" value="$guessed" />
<input type="hidden" name="word" value="$which" />
<fieldset>
<legend style='color: red'>Your next guess</legend>
<input type="text" name="letter" autofocus />
<input type="submit" value="Guess" />
</fieldset>
</form>
</body>
ENDPAGE;
}
function loadWords() {
global $words;
global $numwords;
$input = fopen("./words.txt", "r");
while (true) {
$str = fgets($input);
if (!$str) break;
$words[] = rtrim($str);
$numwords++;
}
fclose($input);
}
function startGame() {
global $words;
global $numwords;
global $hang;
$which = rand(0, $numwords - 1);
$word = $words[$which];
$len = strlen($word);
$guesstemplate = str_repeat('_ ', $len);
$script = $_SERVER["PHP_SELF"];
printPage($hang[0], $guesstemplate, $which, "", 0);
}
function killPlayer($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You lost!</h1>
<p>The word you were trying to guess was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function congratulateWinner($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You win!</h1>
<p>Congratulations! You guessed that the word was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function matchLetters($word, $guessedLetters) {
$len = strlen($word);
$guesstemplate = str_repeat("_ ", $len);
for ($i = 0; $i < $len; $i++) {
$ch = $word[$i];
if (strstr($guessedLetters, $ch)) {
$pos = 2 * $i;
$guesstemplate[$pos] = $ch;
}
}
return $guesstemplate;
}
function handleGuess() {
global $words;
global $hang;
$which = $_POST["word"];
$word = $words[$which];
$wrong = $_POST["wrong"];
$lettersguessed = $_POST["lettersguessed"];
$guess = $_POST["letter"];
$letter = strtoupper($guess[0]);
if(!strstr($word, $letter)) {
$wrong++;
}
$lettersguessed = $lettersguessed . $letter;
$guesstemplate = matchLetters($word, $lettersguessed);
if (!strstr($guesstemplate, "_")) {
congratulateWinner($word);
} else if ($wrong >= 6) {
killPlayer($word);
} else {
printPage($hang[$wrong], $guesstemplate, $which, $lettersguessed, $wrong);
}
}
//header("Content-type: text/plain");
loadWords();
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
handleGuess();
} else {
startGame();
}
?>

Submitting form to database

I've got everything worked out for my Support Ticket website, except my newticket form isn't posting the values to the database. Here is what I have:
<?php
ob_start();
session_start();
include 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
$error = false;
}
if ( isset($_POST['btn-cancel']) ) {
header("Location: home.php");
exit;
}
if ( isset($_POST['btn-signup']) ) {
// get form results
$text = $_POST['description'];
$text = strip_tags($text);
$userid = $_POST['user'];
$problem = $_POST['problem'];
$room = $_POST['room'];
$status = 1;
$datetime = date('Y-m-d G:i:s');
// description validation
if (empty($text)) {
$error = true;
$textError = "Please describe the problem.";
} else if (strlen($text) > 200) {
$error = true;
$textError = "Description must be less than 200 characters in length.";
}
// dropdown validation
if ($problem < 1){
$error = true;
$problemError = "Please choose a category and problem.";
} else if ($room < 1) {
$error = true;
$roomError = "Please choose a building and a room number.";
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO job (User_UserID,Problem_ProblemID,Status_StatusID,Room_RoomID,Description,Date_Time) VALUES({$userid},{$problem},{$status},{$room},'{$text}',{$dateTime})";
echo '$query';
$res = mysqli_query($conn,$query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully submited ticket";
unset($text);
unset($problem);
unset($room);
unset($datetime);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later.";
}
}
}
}
?>
HTML:
<!DOCTYPE html>
<html>
<head>
<SCRIPT language=JavaScript>
<!--
//function reload(form)
{
//var val=form.type.options[form.type.options.selectedIndex].value;
//self.location='newticket.php?type=' + val ;
}
//function reload2(form)
{
//var val=form.building.options[form.building.options.selectedIndex].value;
//self.location='newticket.php?building=' + val ;
}
function disableselect()
{
<?Php
if(isset($type) and strlen($type) > 0){
echo "document.f1.problem.disabled = false;";}
else{echo "document.f1.problem.disabled = true;";}
if(isset($building) and strlen($type) > 0){
echo "document.f1.room.disabled = false;";}
else{echo "document.f1.room.disabled = true;";}
?>
}
//-->
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dog Tracks - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body onload=disableselect();>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Create New Ticket</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<?php
//Getting the data for first list box
$quer2="SELECT problem_typeid,problem_type FROM problem_type ORDER BY problem_type";
echo "<select name='type' onchange=\"reload(this.form)\"><option value=''>Pick problem category</option>";
//while($result2 = mysql_fetch_array($quer2)) {
foreach (mysqli_query($conn,$quer2) as $result2) {
if($result2['problem_typeid']==$type){echo "<option selected value='$result2[problem_typeid]'>$result2[problem_type]</option>"."<BR>";}
else{echo "<option value='$result2[problem_typeid]'>$result2[problem_type]</option>";}
}
echo "</select>";
$type=$_GET['type'];
// for second drop down list
if(isset($type) and strlen($type) > 0){
$quer="SELECT problemid,problem FROM problem WHERE
Problem_Type_Problem_TypeID={$type} order by problem";
}else {
$quer="SELECT problemid,problem FROM problem order by problem";
}
echo "<select name='problem'><option value=''>What is the problem?</option>";
//while($result = mysql_fetch_array($quer)) {
foreach (mysqli_query($conn,$quer) as $result) {
echo "<option value='$result[problemid]'>$result[problem]</option>";
}
echo "</select>";
//// Add your other form fields as needed here/////
?>
</div>
<span class="text-danger"><?php echo $problemError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<?php
#$building=$_GET['building'];
//Getting the data for first list box
$quer3="SELECT buildingid,building FROM building ORDER BY building";
// for second drop down list
if(isset($building) and strlen($building) > 0){
$quer4="SELECT roomid,roomNum FROM room WHERE
building_buildingID=$building order by roomNum";
}else {
$quer4="SELECT roomid,roomNum FROM room order by roomNum";
}
echo "<select name='building' onchange=\"reload2(this.form)\"><option value=''>In which building?</option>";
//while($result2 = mysql_fetch_array($quer3)) {
foreach (mysqli_query($conn,$quer3) as $result3) {
if($result3['buildingid']==#$building){echo "<option selected value='$result3[buildingid]'>$result3[building]</option>"."<BR>";}
else{echo "<option value='$result3[buildingid]'>$result3[building]</option>";}
}
echo "</select>";
echo "<select name='room'><option value=''>In what room?</option>";
//while($result = mysql_fetch_array($quer)) {
foreach (mysqli_query($conn,$quer4) as $result4) {
echo "<option value='$result4[roomid]'>$result4[roomNum]</option>";
}
echo "</select>";
//// Add your other form fields as needed here/////
?>
</div>
<span class="text-danger"><?php echo $roomError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<textarea cols='72' id='description' rows='6' placeholder="Description">
Please describe the problem here. </textarea>
</div>
<span class="text-danger"><?php echo $textError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-submit">Submit</button>
<button type="submit" class="btn btn-block btn-primary" name="btn-cancel">Cancel</button>
</div>
<div class="form-group">
<hr />
</div>
</form>
</div>
</div>
</body>
</html>
<?php
mysqli_close($conn);
ob_end_flush();
?>
First
if ($problem < 1){
$error = true;
$problemError = "Please choose a category and problem.";
} else if ($room < 1) {
$error = true;
$roomError = "Please choose a building and a room number.";
Oops, you don't close that else if, so your INSERT is always skipped.
The next problem
One part of the code that looks dodgy are these lines:
$datetime = date('Y-m-d G:i:s');
//...
$query = "INSERT INTO job (User_UserID,Problem_ProblemID,Status_StatusID,Room_RoomID,Description,Date_Time)
VALUES({$userid},{$problem},{$status},{$room},'{$text}',{$dateTime})";
^^^^^^^^^^^
Your $dateTime will be something like 2016-12-09 11:43:42, so the SQL statement will be:
INSERT INTO job (...) VALUES(..., 'This is my text', 2016-12-09 11:43:42)
This is a syntax error. Note that your $text field has quotes around it to keep it as a single element, but your date does not. Using '{$dateTime}' will fix this problem, although there is no guarantee that there is no other issue...

Why is my error message not echoing to the screen?

When the user submits a form, the PHP will check to see if the $post was empty, if so, it will set an $error_message variable; thus database INSERT query will not execute. I then attempt to show the error message further on in the code, however it will not display. I have been trying to figure this out for hours and I still cannot find the solution. The funny thing is, this used to work, however I must have implemented something in this file which is preventing the code to execute correctly.
Why is my error message not echoing to the screen (last few lines of code show attempt to echo the error_message)?
<?php require("inc/db.php"); ?>
<?php include("inc/functions.php"); ?>
<?php include ("inc/ChromePhp.php"); ?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set("html_errors", 1);
session_start();
if(!isset($_GET['id'])) {
header("Location: ?id=".getUserId($_SESSION['U_Email']));
}
if(isset($_SESSION["U_Email"])) {
$usersData = getUserInfo($_GET['id']);
$postCount = getPostCount($_GET['id']);
} else {
header('Location: login.php');
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
$post = trim(filter_input(INPUT_POST,"user_post",FILTER_SANITIZE_SPECIAL_CHARS));
if($post == "") {
$error_message = "Please enter something before submitting";
}
if(!isset($error_message)) {
$post = $db->real_escape_string($post);
$postStore = $db->query("INSERT INTO `Post`(P_Body, P_Dateadded, User_U_ID) VALUES ('{$post}', NOW(), '{$_SESSION['U_ID']}' )");
}
}
$dashNav = true;
$cap = true;
$pageTitle = 'Profile';
$name = $usersData['U_Forename'] . " " . $usersData['U_Surname'];
$gender = $usersData['U_Gender'];
$bio = $usersData['U_Biography'];
$team = $usersData['U_Team'];
$city = $usersData['U_City'];
include("inc/header.php");
?>
<?php if(userExists($_GET['id'])) { ?>
<section>
<div class="wrapper">
<?php
if($_SESSION['U_ID'] != $_GET['id']) {
$testFollow = "SELECT `Following`.F_ID, `Following`.U_ID FROM `Following`
WHERE U_ID = '{$_SESSION['U_ID']}' AND F_ID = '{$_GET['id']}'";
$testFollowResult = $db->query($testFollow);
if ($testFollowResult->num_rows > 0) {
echo "<button class='lift' href='#'>Unfollow Driver</button>";
} else {
echo "<button class='lift' href='#'>Follow Driver</button>";
}
}
?>
<?php if (isset($error_message)) {
// This code will not echo!
echo "<h2>".$error_message."</h2>";
}
?>
</div>
<div class="section-b">
<div class="grid">
<div class="row">
<div class="col-wd-12">
<div class="col">
<form id="share" name="share" action="profile.php" method="post">
<textarea id="post" name="user_post" placeholder="What's happening?"> </textarea>
<span id="errorpost" class="error">You must input something something before sending</span>
<?php
echo "<div class='g-recaptcha' data- sitekey='6LfNTB0TAAAAAKEw9zfnFzvGCXF9MuYTkdB144x1
'></div>"; ?>
<button onclick="return postCheckValidate();" type="submit">Share</button>
</form>
</div>
</div>
</div>
</div>
</div>
<?php } ?>

Strange validation error for form

The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.

ISSUE With Utf8 and inserting to mysql

I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
config file
$host = "localhost"; // your mysql server address
$user = ""; // your mysql username
$pass = ""; // your mysql password
$tablename = ""; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
change the collate and character set to utf8 for the table
alter table <some_table> convert to character set utf8 collate utf8_unicode_ci;

Categories