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
header('Content-Type: text/html; charset=utf-8');
mysql_query("SET NAMES utf8");
$num1 = mysql_query("SELECT * FROM `digg` WHERE `url`='{$posts['url']}'");
mysql_query("SET NAMES utf8");
$num = mysql_num_rows($num1);
mysql_query("SET NAMES utf8");
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'digg.com')) {
$error = "Incorrect URL! You must include 'digg.com'";
}else{
mysql_query("SET NAMES utf8");
mysql_query("INSERT INTO `digg` (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 :
Oslash;£Ø³Ù
3 Solutions in your case...
First, you can create your database in the UTF-8 charset, conversions is not needed.
Second, you can test this code...
htmlentities(urldecode( $my_var_to_utf8 ), ENT_QUOTES, 'UTF-8');
If it don't works, try this function...
function to_utf8( $string ) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
if ( preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string) ) {
return $string;
} else {
return iconv('CP1252', 'UTF-8', $string);
}
}
To use...
echo(to_utf8($my_var_to_utf8));
Related
My error because the user inputted a non numerical value, the if else statement to change the value of the incrementing value to a positive number if the user inputs a negative value and the change if the start value is greater that the stop value is not working either.
<?php
$banner = "Self-referring Forms w/Data Validation";
include ("./header.php");
$start = "";
$stop = "";
$incr = "";
$error = "";
$output = "";
$checkResult = false;
$MAX_ITERATIONS = 100;
?>
<h2><?php echo $output; ?></h2>
<h3><?php echo $error; ?></h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<p id="para6">Starting Temperature: <input
type="text" name="starting_number" size="12"<?php ?>/><br/>
<p id="para6">Stop Temperature :
<input type="text" name="stop_number" size="12" /><br/>
<p id="para6">Temperature Increment: <input type="text"
name="increment_number" size="12" /><br/></p>
<input id="para6" type="submit" value="Create Temperature Conversion Table" name="calculate"/>
<?php
error_reporting(E_ERROR | E_PARSE);
try
{
if($_SERVER["REQUEST_METHOD"] == "GET"){
$start = "";
$stop = "";
$incr = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$start=(double)trim($_POST["starting_number"]);
$stop=(double)trim($_POST["stop_number"]);
$incr=(double)trim($_POST["increment_number"]);
$num = (double)($stop-$start)/$incr;
if($start == "" || $stop == "" || $incr == "" || $num == "")
{
//means the user did not enter anything
$error .= "The text boxes cannot be blank.";
echo $error;
}
else if($num>$MAX_ITERATIONS)
{
$error .= "The conditions will cause too many iterations (max. 100), therefore (for the
sake of server resources) your request is denied.";
echo $error;
}
This is where I need help
else if($start >= $stop)
{
$start == $stop;
$stop == $start;
}
else if($incr == "0")
{
$error .= "You must enter a non-zero increment.";
echo $error;
}
else if($incr < "0")
{
$incr == $incr * (-1);
}
else if($start == input type="text" || $stop == input type="text" ||$incr == input
type="text" || $num == input type="text")
{
$error .= "You must enter a numerical value";
echo $error;
}
The rest is just for you to see what the rest of my code looks like
else
{
echo "<table border='1'>";
echo "<tr>";
echo "<th>Celcius</th>";
echo "<th>Fahrenheit</th>";
echo "</tr>";
for($i=$start; $i<=$stop; $i += $incr)
{
echo "<tr>";
echo "<td>". $i . "°</td>";
echo "<td>". (($i * 9/5) + 32 ). "°</td>";
echo "</tr>";
}
echo "</table>";
}
if($error == "")
{
$output = "";
}
else
{
$error .= "<br/>Please try again.";
}
}
}
catch(DivisionByZeroError $e)
{
echo "The text boxes cannot be blank.";
}
catch(Exception $e)
{
echo 'Please Enter correctly';
}
?>
</form>
<?php
include ("./footer.php");
?>
The program is working fine except for the number changing command.
If someone could spot my error that would be greatly appreciated.
The change form comes up but the submit button does not POST to the variable.
change.php
<form class="" action="index.php" method="post">
<p>Min:<input type="number" name="min" value=""></p>
<p>Max:<input type="number" name="max" value=""></P>
<input type="submit" name="valuechange" value="Change">
</form>
index.php
<?php session_start();
?>
<center>
<?php
$minn = 1;
$maxx = 3;
if (isset($_GET["change"])) {
if (isset($_POST["valuechange"])) {
$minn = $_POST["min"];
$maxx = $_POST["max"];
}else {
include("change.php");
}
}
echo "<h1>Guess a number between ". $minn ." and ". $maxx . "</h1>";
if (!isset($_SESSION["number"])) {
$_SESSION["number"] = mt_rand($minn,$maxx);
$_SESSION["counter"] = 0;
}
if (isset($_POST["guess"])) {
if ($_POST['guess']== $_SESSION['number']) {
echo "<br><br><br><br>Correct<br>"."Your number was ". $_SESSION["number"]."<br>"."<a href='reset.php'>Play Again </a>";
session_destroy();
echo "<br><a href='index.php?change=true'>Change Numbers</a>";
}else {
$_SESSION["counter"] = $_SESSION["counter"] + 1;
include("form.php");
echo $_SESSION["counter"]. " Guesses<br>";
if ($_POST["guess"] > $_SESSION["number"]) {
echo "Incorrect your number is too big try a smaller number.";
} else if ($_POST["guess"] < $_SESSION["number"]) {
echo "Incorrect your number is too small try a larger number.";
}
echo "<br><a href='reset.php'>RESET </a>";
}
}else {
include("form.php");
}
?>
</center>
I'm starting to make a little quiz page, where there are 3 choices opportunities. I here by to find out about what it is right,
Html
<p><input type="radio" name="svar[1]"><?php echo $svar1;?></p>
<p><input type="radio" name="svar[2]"><?php echo $svar2;?></p>
<p><input type="radio" name="svar[3]"><?php echo $svar3;?></p>
Php
if($_POST["svar"][1] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][2] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][3] == $ok)
{
$_POST["rigtigok"] = 1;
}
what I would like it / it must be outward is $ok is true with what comes from the database
if it shows like this:
$_POST["svar"][3] == $ok
then it will at the same time the $ok = 3
then it will also say that the content fits with what is being clicked by radio contents.
My Content from the database looks like this:
<form action="#" method="post">
<?php
if ($stmt = $this->mysqli->prepare('SELECT id, title, svar1, svar2, svar3, ok FROM quiz ORDER BY RAND() LIMIT 1')) {
$stmt->execute();
$stmt->bind_result($id, $title, $svar1, $svar2, $svar3, $ok);
while ($stmt->fetch()) {
?>
<h3><?php echo $title;?></h3>
<div style="padding:5px 10px;">
<p><input type="radio" name="svar[1]"><?php echo $svar1;?></p>
<p><input type="radio" name="svar[2]"><?php echo $svar2;?></p>
<p><input type="radio" name="svar[3]"><?php echo $svar3;?></p>
</div>
<?php
if(isset($_POST["ok"]))
{
if($_POST["svar"][1] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][2] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][3] == $ok)
{
$_POST["rigtigok"] = 1;
}
}
}
$stmt->close();
} else {
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
?>
<br/>
<input type="submit" name="ok" value="Nyt Spørgsmål" class="new upload_boxxen">
</form>
<?php
echo print_r($_POST["svar"]);
if(isset($_POST["ok"]))
{
if($_POST["rigtigok"] == 1)
{
echo "test";
}
}
EDIT
How it is that I do not get anything out of $_POST["rigtigok"] to be the first me later that I can give my 3 points for his correct answer?
I did something like this :
devis2.php
<script type="text/javascript" src="quote_validation2.js"></script>
<?php
$ddcount = 1;
foreach ($_POST as $key => $value) {
$$key = $value;
}
If (isset($_POST['garment_type']) && $ddcount == 1) {
$post_to = "devis2-resultats.php";
$ddcount = $ddcount + 1;
} Else {
$post_to = "devis2.php";
}
?>
<div style="float:right; display: block;"><img style="border: none;" border="0" src="images/quote-again.gif" width="120" height="16" /></div><br/><br/>
<form name="instantquote" onSubmit="return validator(this)" method="post" action="<?php echo $post_to; ?>">
Au bac:<br/><select multiple size="3" name="garment_type" class="quoteFields" tabindex="1">
<?php
If (isset($_POST['garment_type'])) {
echo "<option value=\"$garment_type\" selected>$garment_type</option> \n";
} Else {
echo "<option value=\"0\" selected>Choisir un soin</option> \n";
}
?>
<option value="soin1">soin1</option>
<option value="soin2">soin2</option>
</select><br/>Longueur des cheveux*:<br/>
<select name="colors_back" class="quoteFields" tabindex="5" size="1" onChange="Javascript:document.instantquote.submit()" >
<?php
If (isset($_POST['colors_back'])) {
echo "<option value=\"$colors_back\" selected>$colors_back</option> \n";
} Else {
echo "<option value=\"0\" selected>Choisir une longueur</option> \n";
}
?>
<option value="+ de 25 cm">+ de 25 cm</option>
<option value="- de 25 cm">- de 25 cm</option>
</select>
<input type="hidden" name="ddcount" value="<?php echo $ddcount; ?>">
<br/><br/><input type="submit" value="Obtenir votre devis" name="quote" class="quoteSubmit" tabindex="20">
</form>
devis2-resultats.php
<?php
foreach ($_POST as $key => $value) {
$$key = $value;
}
include("quote-prices2.php");
?>
<br/><br/><b>Au bac:</b> <?php echo $garment_type; ?><br/><br/>
<?php
If (!isset($_POST['ind_numbers'])) {
} Else {
?>
Individual Numbers:<?php echo $ind_numbers; ?><br/><br/>
<?php
}
If (!isset($_POST['ind_names'])) {
} Else {
?>
Individual Names: <?php echo $ind_names; ?><br/><br/>
<?php
}
If (!empty($email)) { ?>
<br/><br/><b>Envoyé à:</b> <?php echo $email; ?><br/><br/>
<?php
}
?>
<br/><br/><div style="font-size:16px; background-color:#fff; color:#bf3d71;"> <b>Total:</b> <?php $dectotal = sprintf('%0.2f', $total); echo $dectotal; ?> $</div><br/><br/><br>
quote-prices2.php
<?php
// INCOMING VARIABLES FOR PROCESSING: garment_type, garment_color, quantity, colors_front, colors_back, ind_numbers, ind_names
// GARMENT TYPE PRICE
$flash_charge = 0;
switch ($garment_type) {
case "soin1":
$price_garment_type = 6.00;
break;
case "soin2":
$price_garment_typea = 7.00;
break;
}
if ($_POST['garment_type'] === 'soin2') {
switch ($colors_back) {
case "+ de 25 cm":
$price_garment_typea = $price_garment_typea + 50;
break;
}}
$total_garment_pricing = $price_garment_type + $price_garment_typea;
$total_additionals = $total_garment_pricing;
$total = $total_garment_pricing + $total_additionals;
$per_garment_price = $total/2;
$total = $total/2;
?>
**quote_validation2.js**
function validator(form) {
if (form.colors_back.value == 0) {
alert("Vous devez sélectionner une longueur de cheveux.");
return false;
}
return true;
}
function CalcKeyCode(aChar) {
var character = aChar.substring(0,1);
var code = aChar.charCodeAt(0);
return code;
}
function checkNumber(val) {
var strPass = val.value;
var strLength = strPass.length;
var lchar = val.value.charAt((strLength) - 1);
var cCode = CalcKeyCode(lchar);
/* Check if the keyed in character is a number
do you want alphabetic UPPERCASE only ?
or lower case only just check their respective
codes and replace the 48 and 57 */
if (cCode < 48 || cCode > 57 ) {
var myNumber = val.value.substring(0, (strLength) - 1);
val.value = myNumber;
}
return false;
}
I'am very bad at php developement. At this point if I select soin1 & soin2 it display one price only. soin1 = 6 & soin2 = 7 if they are both selected I'd like to obtain 13 as a result. And of course if soin1,soin2 & + de 25 cm are selected I'd like to obtain 63 as a result. The question is how can I make multi select work to obtain the addition of soin1 & soin2. See the script here.
My intention is to retrieve data from a database and have created the following functions but receive an undefined function, grades, error message. The code is as follows:
<form action="processor.php" method="post">
<h4>Question # 1</h4>
<p>What grade are you in?</p>
<label class="checkbox"><input type="checkbox" name="grade" value="1"> Freshmen</label>
<label class="checkbox"><input type="checkbox" name="grade" value="2"> Sophomore</label>
<label class="checkbox"><input type="checkbox" name="grade" value="3"> Junior</label>
<label class="checkbox"><input type="checkbox" name="grade" value="4"> Senior</label>
<h4>Question # 2</h4>
<p>What is your current GPA?</p>
<select name="gpa">
<option value="4">3.5 or above</option>
<option value="3">3.0-3.4</option>
<option value="2">2.5-2.9</option>
<option value="1">2.0-2.4</option>
<option value="0">Lower</option>
</select>
<h4>Question # 3</h4>
<p>Where do you excel the most academically?</p>
<select name="school" multiple="multiple">
<option value ="1">Mathematics</option>
<option value ="2">Literature</option>
<option value ="3">History</option>
<option value ="4">Humanities</option>
<option value ="5">Science</option>
</select>
Then the PHP file that processes the form submission:
<?php
require_once('processor.php');
class Processor {
#code
function get_response($id) {
$dsn = "mysql:host=localhost;dbname=user";
$username = "root"; // database username
$password = "stewie12"; // database password
try {
$enter = new PDO($dsn, $username, $password);
$sql = "SELECT response FROM recommendations WHERE id = ? ";
$new_item = $enter->prepare($sql);
$new_item->setFetchmode(PDO::FETCH_ASSOC);
$new_item->execute(array($id));
foreach($new_item as $nw) {
return $nw['response'];
}
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
return "";
}
function GetWeird () {
$santiago="1992";
if ($santiago="1992") {
$id = 1;
} else {
$id = 2;
}
echo $this->get_response($id);
}
function Grades () {
$grade = $_POST['grade'];
if ($grade =="1") {
echo "You're a freshmen";
} elseif ($grade == "2") {
echo "You're a sophomore";
} elseif ($grade == "3") {
echo "You're a junior.";
} elseif ($grade == "4") {
echo "You're a senior.";
} else {
echo "Something is wrong.";
}
}
function Gpa () {
$gpa = $_POST['gpa'];
if ($gpa =="1") {
echo "You strongly need to up your GPA.";
} elseif ($gpa == "2") {
echo "You're an average student.";
} elseif ($gpa == "3") {
echo "You're an above average student.";
} elseif ($gpa == "4") {
echo "You're an excellent sudent.";
} else {
echo "Something is wrong.";
}
}
function School () {
$school = $_POST['school'];
if ($school =="1") {
echo "You're into Math";
} elseif ($school == "2") {
echo "You're into Lit";
} elseif ($school == "3") {
echo "You're into history.";
} elseif ($school == "4") {
echo "You're into humanities.";
} elseif ($school == "5") {
echo "You're into science.";
} else {
echo "Something is wrong.";
}
}
And the view page:
<?php $processor = new Processor(); ?>
<h4>Question # 1</h4>
<p><?php Grades($grade); ?></p>
<h4>Question # 2</h4>
<p><?php Gpa($gpa); ?></p>
<h4>Question # 3</h4>
<p><?php School($school); ?></p>
To access the class function use below code,
You have to use it like this $class_variable->function_name()
<?php $processor = new Processor(); ?>
<h4>Question # 1</h4>
<p><?php $processor->Grades($grade); ?></p>
<h4>Question # 2</h4>
<p><?php $processor->Gpa($gpa); ?></p>
<h4>Question # 3</h4>
<p><?php $processor->School($school); ?></p>