guys. When I type anything on cyrillic like: Цветана Пиронкова, and click submit (into the table), it is showing it (and saving it in the mysql table), like that: Цветана Пиронкова
And I don't have any ideas how to fix it. I think that the problem comes from htmlspecialchars, but I don't know. Here is my index file:
<?php // connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM players")
or die(mysql_error());
mysql_query("SET NAMES UTF8");
// display data in table
echo "<p><b>View All</b></p>";
echo "<table class=\"table table-bordered table-hover\" border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Mqsto</th> <th>Ime</th> <th>Tochki</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['mqsto'] . '</td>';
echo '<td>' . $row['ime'] . '</td>';
echo '<td>' . $row['tochki'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p><br><br>
Here is my new.php file:
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($mqsto, $ime, $tochki, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Mqsto: *</strong> <input type="text" name="mqsto" value="<?php echo $mqsto; ?>" /><br/>
<strong>Ime: *</strong> <input type="text" name="ime" value="<?php echo $ime; ?>" /><br/>
<strong>Tochki: *</strong> <input type="text" name="tochki" value="<?php echo $tochki; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
mysql_query("SET NAMES UTF8");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$mqsto = mysql_real_escape_string(htmlspecialchars($_POST['mqsto']));
$ime = mysql_real_escape_string(htmlspecialchars($_POST['ime']));
$tochki = mysql_real_escape_string(htmlspecialchars($_POST['tochki']));
// check to make sure both fields are entered
if ($mqsto == '' || $ime == '' || $tochki == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($mqsto, $ime, $tochki, $error);
}
else
{
// save the data to the database
mysql_query("INSERT players SET mqsto='$mqsto', ime='$ime', tochki='$tochki'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: ranglista.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','');
}
?>
Have you setted the database charset to UTF-8 and used this inside your html?
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
Remember also that UTF-8 cyrillic inside database takes 2 byte, so pay attention when you set varchar or similar size (if you want to display 3000 character you should set a size of 6000)
Add to the top of your new.php file
echo "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
Related
I'm trying to use an HTML dropdown form in order to let the user choose which table from the database to display. This part works fine, but I want them to be able to add to whichever table they choose. I've created the form for it but once they hit submit on that form it unloads the table they selected and fails to add the data to the table.
This is the code for the main page; body.php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<div>
<label for="dbselect">Select Table:</label><br>
<select name="dbselect" id="dbselect">
<option value=""><-- Choose Table --></option>
<option value="messages">messages</option>
<option value="messages2">messages2</option>
</select>
</div>
<div>
<button type="submit">Select</button>
</div>
</form>
<?php
session_start();
include 'get.php';
$_SESSION["dbselect"] = filter_input(INPUT_POST, 'dbselect', FILTER_SANITIZE_STRING);
if ($_SESSION["dbselect"] == "messages") {
dbMessages("*");
include 'Forms/contact_form.php';
}
if ($_SESSION["dbselect"] == "messages2") {
dbMessages2("*");
}
?>
</body>
This is the code that actually prints the tables, which I believe works fine; get.php:
<?php
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
function dbMessages($selector) {
include 'db.php';
$query = "SELECT $selector FROM messages";
$res = mysqli_query($conn,$query);
display_data($res);
}
function dbMessages2($selector) {
include 'db.php';
$query = "SELECT $selector FROM messages2";
$res = mysqli_query($conn,$query);
display_data($res);
}
And this is the code that is supposed to display the form and upload the data into the table; contact_form.php:
<?php
include 'db.php';
if ((isset($_POST["Submit"])) && (!empty($_POST["txtName"])) && (!empty($_POST["txtPhone"])) && (!empty($_POST["txtEmail"])) && (!empty($_POST["txtMessage"]))) {
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];
$query = "insert into messages(ID, name, email, phone, message) values (NULL,
'$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";
$res = mysqli_query($conn , $query);
mysqli_close($conn);
unset($_POST);
echo "<meta http-equiv='refresh' content='0'>";
}
echo '
<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="index.php?send=1" target="_self">
<p>
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName" >
</p>
<p>
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
</p>
<p>
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
</p>
<p> </p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset>
'
?>
This is the observed process:
I select which table to display using dropdown menu and hit select.
Selected table successfully appears with its form.
I enter data into form and hit submit.
The dropdown menu returns to it's default state and the table unloads.
Entered data fails to be added to table.
This is the expected process:
I select which table to display using dropdown menu and hit select.
Selected table successfully appears with its form.
I enter data into form and hit submit.
Selected table stays on the page and submitted data is successfully added.
It should be noted that the contact_form.php file is only for the first table, messages, and not for messages2.
This line in your body.php:
$_SESSION["dbselect"] = filter_input(INPUT_POST, 'dbselect', FILTER_SANITIZE_STRING);
runs every time that page is called, regardless of whether the form containing the dropdown has been submitted or not.
This therefore overwrites the Session value before your code has chance to check what it is. This means that when the contact form is submitted, it still tries to get the dbselect value from $_POST, will fail, and therefore set the Session value incorrectly, removing what was set when the table selection form was last submitted.
You just need to check whether that form has been submitted before overwriting the Session value.
Also FILTER_SANITIZE_STRING is deprecated, you should stop using it, and you don't need that sort of filter in this context anyway.
if (isset($_POST["dbselect"])) {
$_SESSION["dbselect"] = $_POST["dbselect"];
}
I did a form which adds record to database and it shows in HTML table.
One of the column in form and database is "country". I would like to insert a right flag icon beside the "country" column and I'd like to make it from form. I added example photo
Could you help me with any idea?
Form
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style2.css">
</head>
<body>
<?php
if (isset($_GET["date"]) ){
$date = $_GET["date"];
$country = $_GET["country"];
$city = $_GET["city"];
$place = $_GET["place"];
if( empty ( $date ) || empty ($country) || empty ($city) || empty ($place)){
echo "Wypelnij wszystkie pola";
} else {
$conn = new mysqli("localhost", "root", "", "tour");
$odp = $conn->query("INSERT INTO trasy (date, country, city, place)
VALUES ('$date', '$country', '$city', '$place')");
header("Location: index5.php");
if ($odp) {
echo "Dodano koncert";
}else{
echo "Nie udalo sie dodac";
}
$conn->close();
}
}
?>
<div id="login">
<form method="GET" action="index5.php">
<table id="customers">
<input name="date" type="date" placeholder="Date..."><br>
<input name="country" type="text" placeholder="Country..."><br>
<input name="city" type="text" placeholder="City..."><br>
<input name="place" type="text" placeholder="Place..."><br>
<input type="submit" value="OK">
</table>
</form>
</div>
</body>
</html>
HTML table
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style3.css">
</head>
<body>
<table id="customers">
<tr>
<th>Date</th>
<th>Country</th>
<th>City</th>
<th>Place</th>
<th>Info</th>
</tr>
<?php
$conn = new mysqli("localhost", "root", "", "tour")
or die ("Błąd");
$wynik = $conn->query("SELECT * FROM trasy ORDER BY date DESC");
if ($wynik->num_rows > 0){
while ( $wiersz = $wynik->fetch_assoc() ){
echo "<tr>";
echo "<td>" . $wiersz["date"] . "</td>";
echo "<td>" . $wiersz["country"] . "</td>";
echo "<td>" . $wiersz["city"] . "</td>";
echo "<td>" . $wiersz["place"] . "</td>";
echo "<td>" . $wiersz["info"] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "Nic tu nie ma";
}
$conn->close();
?>
</table>
</body>
</html>
I will address only your question but keep in mind you have all sort of wrong things with your code starting with security.
I will just point you in direction what I think is best for you to go.
First of all upload all flags in one directory on server. You can use img or you can use CSS svg like this one for example.
Second, don't make people type there country in input field at all (that way you make sure values for same country will be the same), make that a drop-down with pre-populated all countries and assign a value to each.
Example of value for CSS icons that I provided link for:
If user chooses Germany from drop-down you store in country field value: gr.
That way when you call your country you can do that like this:
echo '<td><span class="flag-icon flag-icon-' . $wiersz["country"] . '"></span></td>';
Which will produce for Germany:
<td><span class="flag-icon flag-icon-gr"></span></td>
You can do same thing just with HTML img tags. Just storing the flag value as img src.
I believe this is best way to go. Other that that you would need to have a whole lot of PHP switch statements.
EDIT:
Additionally if you want to have country name and flag store both of them as value in select and on database input separate it and store it in two columns like this:
<select id="country">
<option value="Croatia | hr">Croatia</option>
<option value="Germany | gr">Germany</option>
<select>
$country = mysqli_real_escape_string($_GET['country']);
$pieces = explode(" | ", $country);
$countryname = $pieces[0]; // piece1
$flag = $pieces[1]; // piece2
I wish to input a number into a database based of a drop down menu consisting of data from another table.
Links table:
Category table:
So basically my drop down will consist of the category.cat written information. But when I submit the form it will input category.id into the links.catID column in the database.
The code I have so far is:
<?php
// since this form is used multiple times in this file, I have made it a
function that is easily reusable
function renderForm($links, $url, $catID, $type, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != ''){
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Link Title: *<br></strong> <input type="text" name="links" size="40" value="<?php echo $links; ?>" /><br><br/>
<strong>URL: *<br></strong> <input type="text" name="url" size="40" value="<?php echo $url; ?>" /><br><br/>
<?php
require 'db/connect.php';
echo" <strong>Category: *<br></strong>";
echo "<select name='catID' id='catID'>";
$sql = "SELECT * FROM links";
$results = $db->query($sql);
if($results->num_rows){
while($row = $results->fetch_object()){
echo "<option>";
echo "{$row->catID}";
echo "</option>";
}
} echo "</select><br>";
?>
<br>
<strong>Type: *<br></strong> <input type="text" name="type" size="40" value="<?php echo $type; ?>" /><br><br/>
<p>* Required</p><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])){
// get form data, making sure it is valid
$links = mysql_real_escape_string(htmlspecialchars($_POST['links']));
$url = mysql_real_escape_string(htmlspecialchars($_POST['url']));
$catID = mysql_real_escape_string(htmlspecialchars($_POST['catID']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
// check to make sure all fields are entered
if ($links == '' || $url == '' || $catID == '' || $type == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($links, $url, $catID, $type, $error);
} else {
// save the data to the database
mysql_query("INSERT links SET links='$links', url='$url', catID='$catID', type='$type'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','','','');
}
?>
Which gives me the following:
May be try this? (Considering the links.links columns and category.cat columns are common)
Store the value of dropdown in a variable say $dropdown_selected_option
Getting the id from the category table using sql:
$sql = "Select id from category where cat = '$dropdown_selected_option'";
$result = mysqli_query($conn, $sql);
Later run a query again to update the given fields in second table;
Update links set
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
// Run update query here where $row['id'] has the ID from the category table required.
}
}
My aim to is to Update Value in Database By using Update Query . On my first page i have just displayed database table in webpage. Then by using hyperlink i have to click on Edit to second page "edit.php".While on first page i have to get the value of id and send it to second page. Where a input form is displayed which gets Value casually but Id through hidden tag. On third page getting the values query is implented but the value of id is missing.
First Page
<html>
<head>
<title>Assignment</title>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","");
// Check connection
if (!mysql_connect()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$db=mysql_select_db("assignment",$con);
$result = mysql_query("SELECT * FROM teacher ",$con);
?><table cellpadding="2px" border="2px"><?php
while($row = mysql_fetch_array($result)) {
?> <tr>
<td><a href="edit.php?id=<?php
echo $row['id']; ?>">Edit</a > Delete
</td><td>
<?php
echo $row['id']; ?></td><td> <?php echo $row['name'];?></td><td><?php echo $row['program']; ?></td>
<?php }
?></table><?php
mysql_close($con);
?>
</body>
</html>
Secnod Page edit.php
<html>
<head>
<title>Assignment Edit</title>
</head>
<body>
<?php
$id = $_GET['id'];
?>
<form action="update.php" method="get">
Address <input type="text" name="program"><br>
<input type="hidden" name="id" value='<?php $id?>'>
<input type="submit" name="submit">
</form>
</body>
</html>
Third Page update.php
<html>
<head>
<title>Update Page</title>
</head>
<body>
<?php
$add=$_GET['program'];
$id=$_GET['id'];
$con=mysql_connect("localhost","root","");
// Check connection
if (!mysql_connect()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$db=mysql_select_db("assignment",$con);
$query = "UPDATE teacher SET program='$add' WHERE id =".$id;
echo $query;
$result = mysql_query($query,$con);
/* while($row = mysql_fetch_array($result)) {
echo $row['id'] ." " . $row['name']." ". $row['address']."<br>";
}
mysql_close($con);
*/
?>
</body>
</html>
output
UPDATE teacher SET program='openSource' WHERE id =
you need to change this
<input type="hidden" name="id" value='<?php $id?>'>
to
<input type="hidden" name="id" value='<?php echo $id?>'>
(or)
<input type="hidden" name="id" value='<?=$id?>'>
i have a troubles with my code.
I have html table in index.php (php, mysql)..this:
<?php
require ('../../inc/config.inc.php');
require ('../../inc/ini.php');
mysql_set_charset('utf8');
$sql = "SELECT * FROM {$cfg['tbl_dily']}";
$result = mysql_query($sql)or die(mysql_error());
echo "<table class=\"vypis\">";
echo "<h1 id=\"vypis\">Nabídka náhradních dílů</h1>\n";
$i = 0; //defaultní hodnota pro obarvení řádku
//start cyklu pro výpis z tbl_dily
while ($row = mysql_fetch_array($result)){
//přístup ke sloupcum tbl_dily
$part_id =$row['part_id'];
$img150 =$row['img150'];
$nazevdilu =$row['nazev'];
$vyrobce =$row['vyrobce'];
$model =$row['model'];
$cena =$row['cena'];
//start --- coloring every 2nd row of table
$i=1-$i;
$trclass="radek".$i;
//end --- coloring every 2nd row of table
echo "<tr class=\"".$trclass."\">\n";
if($img150 == null){ // podmínka pro existenci fotografie produktu
echo "<td class=\"img150\"> <img class=\"obrazek\" src=\"fotoneni.gif\"/> </td>\n";
}
else {
echo "<td class=\"img150\"> <img class=\"obrazek\" src=\"".$img150."\"/> </td>\n";
}
echo "<td class=\"nazevdilu\">".$nazevdilu."</td>\n";
echo "<td class=\"modely\">".$vyrobce." ".$model."</td>\n";
if($cena == 0){ //podmínka pro existenci přesné ceny produktu nebo "dohodou"
echo "<td class=\"cena\">dohodou</td>\n";
}
else{
echo "<td class=\"cena\">".$cena." Kč"."</td>\n";
}
echo "</tr>\n";
}
//konec cyklu pro výpis z tbl_dily
echo "</table>\n";
?>
So I have linked out part_id with no problems. Problems shows when I want to see detail of some product. My detail.php looks like this now:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<?php
require ('../../inc/config.inc.php');
require ('../../inc/ini.php');
mysql_set_charset('utf8');
$part_id=$_GET['part_id'];
$data = mysql_query("SELECT * FROM {$cfg['tbl_dily']} WHERE part_id='$part_id'") or die(mysql_error());
while ($detail = mysql_fetch_array($data)){
$id =$detail['part_id'];
}
?>
<title><?php $id; ?></title>
</head>
<body>
<div class="detail">
<span id="detail_id">Výpis nabídky id <?php $id; ?></span>
<div class="detail_foto">
</div>
<div class="detail_info">
</div>
</div>
</body>
</html>
I need to help at least with getting part_id number in page title of detail.php. I dont understand so much how $_GET works..I hope you somebody show me how-to..
THANKS for helping me out:))
Your explanation is not terribly nice. You should maybe edit the Question and explain where the problem is at. But for now, let me just explain '$_GET'
'$_GET' is a way to deliver Data from one PHP Script to another. You can find them in almost every Formular. As you can see in the Code below, there is a simple way that sends Data to an "action.php" - the attribute "method" is for telling the formular what you want to do. You should maybe take a look at both options because GET displays the data you want to deliver in the link. Your user could start manipulating that which would be a very unsafe thing in your case because you work with mysql-Databases. Also you should take a look at Mysql String escaping.
Back to the topic: The HTML below would redirect $_GET['name'] AND $_GET['age'] to the action.php where you can work with those.
<form action="action.php" method="get">
<p>Your ame: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>