Display accented characters - php

In command line, sqlite correctly displays the accented characters contained in my database.
In PHP, echo shows me correctly as well.
But when I do a query from my PHP page, it does not display correctly. I can not find where the encoding problem is.
Thank you in advance for your help.
<?php
$db = new SQLite3('database.sqlite');
if(isset($_GET['search'])) {
$rec = htmlentities($_GET['search']);
} else {
$rec = '';
}
$result3 = $db->query('SELECT lastname,firstname,phone,location FROM rh WHERE name != "" AND lastname || " " || firstname || " " || location LIKE "%'.$rec.'%" ORDER BY name asc LIMIT 25');
?>
The HTML form :
<form action="" method="get">
<input type="search" name="search" value="<?php echo $rec; ?>" /> <input type="submit" value="Search" />
</form>
And the results on another php page :
<?php
echo '<h3>Results</h3>';
echo '<tr><th>Name</th><th>Phone</th><th>Location</th></tr>';
while ($row = $result3->fetchArray(SQLITE3_ASSOC)) {
echo '<tr><td>' . $row['lastname'] . ' ' . $row['firstname'] . '</td><td>' . $row['phone'] . '</td><td>' . $row['location'] . '</td></tr>';
}
$db->close();
?>

Maybe you need to specify the propper encoding in your HTML-Head e.g.:
<html>
<head>
<meta charset="utf-8">
...
</head>
And/or you need to de/encode your data before output utf8_encode();.

Related

Arabic Text in PHP not searched from TextBoX

The code below searches employees on basis of employee number entered in textbox or first name but I have the first name in Arabic and it is not matching. Image is attached which shows priperly arabic on broser but not it is searched by textbox I dont know why
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
<link rel="stylesheet" href="css/insert.css" />
<link rel="stylesheet" href="css/navcss.css" />
</head>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<!--HTML form -->
<div class="form_div">
<h3>Search Records:</h3>
<p>You may search by Employee Number</p>
<form method="post" action="search.php?go" id="searchform">
<input type="text" class="input" name="emp_number">
<input type="submit" class="input" name="submit" value="Search">
</form>
<?php
include 'connect-db.php';
//do something here in code
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[a-zA-Z0-9,]+$/", $_POST['emp_number'])){
//if(preg_match("/\p{Arabic}/u", $_POST['first_name'])){
$emp_number=$_POST['emp_number'];
//$first_name=$_POST['first_name'];
//connect to the database
//$db=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
//$mydb=mysql_select_db("mydb");
//-query the database table
//mysqli_query($connection,"SET CHARACTER SET utf8");
$sql="SELECT * FROM employees WHERE emp_number LIKE '%" . $emp_number . "%' OR first_name LIKE '%" . $emp_number."%'";
//-run the query against the mysql query function . $name .
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$FirstName =$row['first_name'];
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>First Name</th> <th>Last Name</th><th>Employee Number</th><th>Department</th><th>Email</th><th>Total Printers</th><th>Total Scanners</th><th>Total PCs</th><th>Total Telephones</th></tr>";
//-display the result of the array
echo "<tr>";
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '<td>' . $row['emp_number'] . '</td>';
echo '<td>' . $row['department'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['total_printers'] . '</td>';
echo '<td>' . $row['total_scanners'] . '</td>';
echo '<td>' . $row['total_pc'] . '</td>';
echo '<td>' . $row['total_phones'] . '</td>';
echo '<td class="forscreen">View</td>';
echo '<td class="forscreen">Edit</td>';
echo '<td class="forscreen">Delete</td>';
echo '<td class="forscreen">View Accessories</td>';
echo '<td class="forscreen">Add Accessories</td>';
//echo '<button class="btnPrint" type="submit" value="Submit" onclick="window.print()">Print</button>';
//echo '<button class="btnPrevious" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>';
/*echo "<ul>\n";
echo "<li>" . "" .$FirstName . "</li>\n";
echo "</ul>"; */
echo "</tr>";
}
// close table>
echo "</table>";
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
<div class="forscreen">
<br />
<button class="btnPrint" type="submit" value="Submit" onclick="window.print()">Print</button>
<button class="btnPrevious" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>
</div>
</div>
</div>
</body>
</html>
You should check your database tables default collation. I often work with korean charachters and I always make sure everything is set tu utf8. (HTML / PHP headers and DB tables collation).
This may not be required in modern versions of PHP, but on the very first line of your file, add the following:
<?php
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
?>

Error message not displaying html forms using php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a basic form trying to validate that a checkbox is selected, at the moment it is not allowing it to go through (expected) however my error message is not displaying on the same page, it is probably something really small that is missing.
It not displaying the error, a span class can be seen in the html below.
Where's the problem?
php:
<?php
require_once 'db/connect.php';
$error='';
$success='';
if (isset($_POST['submit'])){
if ( (isset($_POST['checkbox'])) && (isset($_POST['competitorDelete'])) ) {
$checkbox = $_POST['checkbox'];
for ($i=0;$i<count($checkbox);$i++) {
$delete_comp = $checkbox[$i];
$query = $con->query("SELECT Forename, Surname FROM student WHERE Student_ID = '" . $delete_comp . "'");
$row = mysqli_fetch_assoc($query);
$success = $row['Forename'] . ' ' . $row['Surname'] . ' has been deleted as a competitor from any events they were submitted for <br>';
$query= $con->query("DELETE FROM competitors WHERE Student_ID = '" . $delete_comp . "'");
}
}
elseif (isset($_POST['checkbox'])) {
$checkbox = $_POST['checkbox'];
for ($i=0;$i<count($checkbox);$i++) {
$delete_student = $checkbox[$i];
$query = $con->query("SELECT Forename, Surname FROM student WHERE Student_ID = '" . $delete_student . "'");
$row = mysqli_fetch_assoc($query);
$success = $row['Forename'] . ' ' . $row['Surname'] . ' has been deleted as a student <br>';
$query= $con->query("DELETE FROM student WHERE Student_ID = '" . $delete_student . "'");
}
}
else {
$error = 'A student must be selected';
}
}
?>
html:
<?php
session_start();
require_once 'db/checkuserloggedin.php';
include 'db/header.php';
include 'deletestudent.php';
echo '<h3> Delete students </h3>';
echo "<form method =\"POST\">";
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Forename, Surname, Student_ID " .
"FROM student, teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")) {
if ($student_result->num_rows) {
echo '<table>';
while ($row1 = $student_result->fetch_assoc()) {
echo '<tr>';
echo '<td>';
echo $row1['Forename'] . ' ' . $row1['Surname'];
echo '</td>';
echo '<td>';
echo '<input type="checkbox" name="checkbox[]" value="' . $row1['Student_ID'] . '">';
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
}
echo 'Delete competitor data only<input type="checkbox" name="competitorDelete">' . '<br>';
echo '<input type="submit" name="submit" value ="Delete">';
echo '<input type="reset" value ="Reset">';
echo '<span class="error"><?php echo $error;?></span>';
echo "</form>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Entry form</title>
</head>
<body>
<div id="logoutbutton">
<button class="btn" onclick="location.href='logout.php'">Logout</button>
</div>
<link rel="stylesheet" type="text/css" href="styles.css">
</body>
</html>
The reason why your error is not showing is because you're already inside PHP in doing an echo and have PHP tags.
echo '<span class="error"><?php echo $error;?></span>';
You can either do: (escaping double quotes for the CSS class name)
echo "<span class=\"error\">$error</span>";
or concatenate the $error variable:
echo '<span class="error">'.$error.'</span>';
Plus, variables do not get parsed inside single quotes, unless concatenated.

refresh = on submit in php, how to fix it?

I am creating an insert process in php but I have a problem in my code. when I refresh my page, it will also submit and insert the data.
here is my code :
<form action="/drupal/node/1" method="post">
Name: <input type="text" name="name" />
Price: <input type="text" name="price" />
Minutes: <input type="text" name="minutes" />
<input type="submit" />
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_select_db("zain", $con);
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['minutes']))
{
$val_name = $_POST['name'];
$val_price = $_POST['price'];
$val_min = $_POST['minutes'];
$max_id_sql = mysql_query("SELECT MAX(id) FROM card_category");
$data = mysql_fetch_array($max_id_sql);
if ($data[0]==0)
{
$val_id = 1;
}
else
{
$val_id = $data[0] + 1;
}
mysql_query("INSERT INTO card_category (id, name, price, minutes) VALUES ($val_id,'$val_name',$val_price,$val_min )");
$_POST['name'] == NULL;
$_POST['price'] == NULL;
$_POST['minutes'] == NULL;
}
$result = mysql_query("SELECT * FROM card_category");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>mins</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (isset($_POST['lastname']))
{
print $_POST['lastname'];
}
mysql_close($con);
?>
my question is, how can I handle when I refresh the page and it will not submit the data?
thanks in advance
When you get the POST submission:
Process the data
Return a Redirect response
Get a GET request from the browser on the URL you redirect to
Respond to that with the HTML
If the browser is refreshed, it will resubmit the GET request which your PHP won't use to modify the database.
This is the POST-REDIRECT-GET pattern. There are some more details in this blog entry (which also has example PHP code in the comments).
How to fix refresh the page do not post the value using php:
if ($_SERVER['HTTP_CACHE_CONTROL']=="")
{
// process the data
}
If you look at $_SERVER['REQUEST_METHOD'] variable, it will say 'POST' when the user submitted data and 'GET' when he did not. So:
if($_SERVER['REQUEST_METHOD']=='POST')
{
// process the data
}
By the way, your code is eminently vulnerable to SQLI attacks ...

Session array keeps overwriting rather than adding to itself

Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.

Dynamically create form elements with php

This short program is suppose find the column names of a table X, and create a form with at least one text field and one select element that contains all the names of the columns of the table. With that information, the user can perform a search on this table and further specify on which column he would like to do the search. I would like it for the user to be able to add more text fields with matching select elements, just in case he wants to refine his search.
How can I dynamically add those extra fields when ever the user press a button?
<?php
$table_name = "tablename";
mysql_connect("localhost", "root", "");
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table_name'";
$result = mysql_query($query);
$column_names="";
while($row = mysql_fetch_array($result)){
$column_names == "" ? $column_names .= $row["COLUMN_NAME"] : $column_names .= "," . $row["COLUMN_NAME"] ;
}
$column_names = explode(",", $column_names);
?>
<html>
<head>
<title>SQLSEARCH</title>
</head>
<body>
<form action="index.php" method="post">
<?php
echo "Search: <input tpe=\"text\" name=\"advtext[]\" /> in ";
echo "<select name=\"advselect[]\">";
foreach($column_names as $value)
echo "<option>" . $value . "</option>";
echo "</select>";
?>
<input type="hidden" name="searchsent" value="1" />
<input type="submit" name="searchbutton" value="Search" />
</form>
<input type="button" name="addattributes" value="Add Search Attributes" / onclick="AddSelect();">
</body>
</html>
This function adds an input element and a select element, every time the user presses the button.
function AddSelect(){
var newInput = document.createElement('input');
newInput.type='text';
newInput.name = 'advtext[]';
<?php
foreach($column_names as $value => $i){
echo "\tvar newOption" . $value . "=document.createElement('option')" . "\n";
echo "\tnewOption" . $value . ".value='" . $i . "';" . "\n";
echo "\tnewOption" . $value . ".innerHTML='" . $i . "';" . "\n\n";
}
?>
var newSelect = document.createElement('select');
newSelect.name = 'advselect[]';
<?php
foreach($column_names as $value => $i){
echo "\tnewSelect.appendChild(newOption" . $value . ")" . "\n";
}
?>
var SubmitButton = document.forms.myform.searchbutton;
document.forms.myform.insertBefore(newInput, SubmitButton);
document.forms.myform.insertBefore(document.createTextNode(" in "), SubmitButton);
document.forms.myform.insertBefore(newSelect, SubmitButton);
}
You can use innerHTML properties for your form . Otherwise use Ajax Functionality to add the extra text box to add dynamically.

Categories