I tried to make a search engine in order to search between 2 dates $dateFrom to $dateTo.
Here what i have tried.:
Index.php:
<?php
require_once 'Connection.simple.php';
$tutorialTitle = "Using Ajax to search a Record with PHP, MySQL and jQuery (Look and Feel by Bootstrap)";
$conn = dbConnect();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title><?php echo $tutorialTitle;?></title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta name="copyright" content="BEHSTANT SOFTWARE | Datasoft Engineering 2013"/>
<meta name="author" content="Reedyseth"/>
<meta name="email" content="ibarragan at behstant dot com"/>
<meta name="description" content="<?php echo $tutorialTitle;?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=stylesheet href="css/style01.css">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<div class="page-header ">
<div class="panel panel-default">
</div>
</div>
<div class="mainContent">
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<label class="col-sm-2 control-label" for="minimum date">employee_id</label>
<div class="input-group col-sm-9">
<input id="DateFrom" name="DateFrom" type="date" class="form-control" placeholder="Type the name" />
<input id="DateTo" name="DateTo" type="date" class="form-control" placeholder="Type the name" />
<span class="input-group-btn">
<button type="button" class="btn btn-default btnSearch">
<span class="glyphicon glyphicon-search"> Search</span>
</button>
</span>
</div>
</div>
</form>
<div class="col-sm-2"></div>
<div class="col-sm-8">
<!-- This table is where the data is display. -->
<table id="resultTable" class="table table-striped table-hover">
<tbody></tbody>
</table>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.10.2.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.btnSearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'search.php',
type: 'get',
DateFrom: {DateFrom: $('input#DateFrom').val()},
DateTo: {DateTo: $('input#DateTo').val()},
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
</body>
</html>
Search.php:
<?php
require_once 'Connection.simple.php';
$conn = dbConnect();
$OK = true;
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
}
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['day']."</td>";
echo "<td>".$row['time_in']."</td>";
echo "<td>".$row['time_out']."</td>";
echo "<td>".$row['worked']."</td>";
echo "<td>".$row['overtime']."</td>";
echo "<td>".$row['less_hours']."</td>";
echo "<td>".$row['transport_in']."</td>";
echo "<td>".$row['Transport_out']."</td>";
echo "</tr>";
}
}
?>
EDIT 1:
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($dateFrom, $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
******I added that to make execute the query but still not working******
<?php
function dbConnect (){
$conn = null;
$host = 'localhost';
$db = 'payroll';
$user = 'root';
$pwd = '';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
//echo 'Connected succesfully.<br>';
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
echo '<p>'.$e.'</p>';
exit;
}
return $conn;
}
?>
******* This is my code for DBconnection*******
My database name is payroll and the table is attendance.
You need to name the parameters inside SQL code.
Please, use the correct case for the columns names. You spelled "less_hours", while in your database this column is called "Less_Hours". And this gave a notice: "Undefined index: less_hours".
I put the output code inside the 1-st if, otherwise $rows will always be undefined for the first time.
This code worked for me:
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE
date >= :date_from AND date <= :date_to ";
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(
array('date_from' => $dateFrom, 'date_to' => $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Day']."</td>";
echo "<td>".$row['Time_In']."</td>";
echo "<td>".$row['Time_Out']."</td>";
echo "<td>".$row['Worked']."</td>";
echo "<td>".$row['Overtime']."</td>";
echo "<td>".$row['Less_Hours']."</td>";
echo "<td>".$row['Transport_In']."</td>";
echo "<td>".$row['Transport_Out']."</td>";
echo "</tr>";
}
}
}
Related
I would like to put a background on my guestbook messages and the font color should be white. How can I change the echo:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(!isset($_SESSION))
{
session_start();
}
include ('dbconnection.php');
include 'checklogin.php';
include 'head_nav.html';
?>
<!DOCTYPE html5>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="descripion" content="Die offizielle Seite von BestFoto">
<meta name="keywords" content="Foto, Fotografie, BestFoto, Business, Architektur, Fashion, Natur">
<meta name="copyright" content="Copyright 2017 by Sharam Etemadi">
<meta name="author" content="Sharam Etemadi">
<title>BestFoto – Kontakt</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="main-content-container">
<div class="content-header-container">
<header class="content-header">
<h1>Kontakt</h1>
</header>
</div><!-- content-header -->
<div class="content-container">
<section class="content">
<p>
Hier könnt ihr Verbesserungsvorschläge oder sonstiges einreichen.
</p>
</section>
</div><!-- content-container -->
</div><!-- main-content-container -->
<form action="" method="post">
<p>Betreff:</p>
<input type="text" name="betreff" placeholder="Betreff?"><br>
<p>Nachricht:</p>
<textarea name="nachricht" placeholder="Ihre Nachricht!"></textarea><br>
<input type="submit" name="submit" value="Absenden!"><br>
</form>
<?php
array_walk ( $_POST, 'cleanmsg' );
array_walk ( $_GET, 'cleanmsg' );
array_walk ( $_REQUEST, 'cleanmsg' );
function cleanmsg(&$value, $key)
{
// keine HTML-Tags erlaubt, außer p und br
$value = strip_tags($value, '<p><br /><b><strong>');
// HTML-Tags maskieren
$value = htmlspecialchars($value, ENT_QUOTES);
// Leerzeichen am Anfang und Ende beseitigen
$value = trim($value);
}
if(isset($_POST['submit'])):
$betreff = $_POST['betreff'];
$nachricht = $_POST['nachricht'];
$userid = $_SESSION['user'];
$StrSQL = "INSERT INTO kontakt (userid_fk,betreff,nachricht,datum)
VALUES (?,?,?,NOW())";
$absenden = $db->prepare($StrSQL);
$absenden->bind_param('iss', $userid, $betreff, $nachricht);
$absenden->execute();
endif;
$StrSQL2 = "SELECT users.benutzername as bn,
kontakt.betreff, kontakt.nachricht, kontakt.datum
FROM users RIGHT JOIN kontakt
ON users.userid = kontakt.userid_fk ORDER BY datum DESC";
$abfrage = $db->query($StrSQL2);
echo 'Es wurden '.$abfrage->num_rows.' Nachrichten gefunden!<br>';
?>
<?php while ($ausgabe = $abfrage->fetch_object()) { ?>
<div class="test">
<b>user:</b><?=!is_null($ausgabe->bn) ? htmlspecialchars($ausgabe->bn) : 'Guest'?>
<br>
<b>Date:</b><?=$ausgabe->date?>
<br>
<b>subject:</b><?=htmlspecialchars($ausgabe->subject)?>
<br>
<b>message:</b>
<br>
<?=htmlspecialchars($ausgabe->message)?>
<br>
<hr>
</div>
<? } ?>
<?php
// rest of the PHP code
$result_total = mysqli_query($db,'SELECT COUNT(*) as `total` FROM kontakt');
$row_total = mysqli_fetch_assoc($result_total);
$gesamte_anzahl = $row_total['total'];
$ergebnisse_pro_seite = 10;
$gesamt_seiten = ceil($gesamte_anzahl/$ergebnisse_pro_seite);
if (empty($_GET['seite_nr'])) {
$seite = 1;
} else {
$seite = $_GET['seite_nr'];
if ($seite > $gesamt_seiten) {
$seite = 1;
}
}
$limit = ($seite*$ergebnisse_pro_seite)-$ergebnisse_pro_seite;
$result = mysqli_query($db,'SELECT `nachricht` FROM `kontakt` LIMIT '.$limit.', '.$ergebnisse_pro_seite);
while ($row = mysqli_fetch_assoc($result)) {
// Ausgabe deiner Daten
}
for ($i=1; $i<=$gesamt_seiten; ++$i) {
if ($seite == $i) {
echo ''.$i.'';
} else {
echo ''.$i.'';
}
}
include 'footer.html';
?>
</div><!-- container -->
</body>
</html>
now with a div class, so I can write this in my css?
Edit: I have inserted the whole code for you, maybe who can overlook which error is present? After I have inserted the accepted answer, I get a white screen and nothing is displayed anymore. Unfortunately I also don't get an error
Do yourself a favor and ditch those echo garbage. Make the HTML first class citizen and then mix PHP into it:
<?php
// php code
?>
<?php while ($ausgabe = $abfrage->fetch_object()) { ?>
<div class="test">
<b>user:</b><?=!is_null($ausgabe->bn) ? htmlspecialchars($ausgabe->bn) : 'Guest'?>
<br>
<b>Date:</b><?=$ausgabe->date?>
<br>
<b>subject:</b><?=htmlspecialchars($ausgabe->subject)?>
<br>
<b>message:</b>
<br>
<?=htmlspecialchars($ausgabe->message)?>
<br>
<hr>
</div>
<? } ?>
<?php
// rest of the PHP code
I am currently trying to build a "ToDo-App" which lets me INSERT text into a database, which will then be displayed. There is a "feature" to delete content based on their ID.
If I input two tasks into my application, I get two table records with ID 1 and 2. When I delete record 1, the record with ID 2 still exists. Thus, the record with ID 2 is listed as the first item in the to-do list.
I have to enter "2" in the "delete input field" to delete the first item from the list! How can I get this to be in sync? Is the ID field appropriate for maintaining the logical / application level order of the tasks?
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
</head>
<?php
$con = mysqli_connect("","root","","todo");
$sql = "SELECT text FROM work";
$res = mysqli_query($con, $sql);
if(isset($_POST["text"]))
{
$eingabe = $_POST["text"];
$query = "INSERT INTO work(text) VALUES('$eingabe')";
mysqli_query($con, $query);
header("Refresh:0");
}
else
{
echo "";
}
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
else
{
echo "";
}
?>
<body>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<form action="index.php" method="post">
<input class="lil-input" name="text" type="text">
<input type="submit" class="lil-button-green" value="Hinzufügen">
</form>
<ol id="liste" class="lil-list">
<?php
while($dsatz = mysqli_fetch_assoc($res))
{
echo "<li>" .$dsatz["text"] ."</li>";
}
?>
</ol>
<form id="form" action="index.php" method="post">
<input class="lil-input" name="del" type="text">
<input type="submit" class="lil-button-red lil-button-small" value=" Löschen ">
</form>
</div>
</div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
var anzahl = $("#liste li").length;
if(anzahl < 1)
{
$("#form").hide();
}
else
{
$("form").show();
}
</script>
</body>
</html>
The pictures:
HTML Output
MySQL Dashboard
As discussed in the comment, you can have multiple checkboxes forming an array parameter: <input name="theName[1]"> with explicit key and name="theName[]" with implicit keys.
Further more, you should use prepared statements to prevent SQL injection attacks. Imagine an attacker sends a request with a single quote ' in the field, i.e. he terminates the SQL string delimiter, and adds arbitrary SQL code. Prepared statements use placeholders and the parameters are sent separately.
You should also handle errors. In the code below errors are output as HTML, however, you should define your own logger function rather than just echo into the stream. This can output HTML on development servers but log to disk on production servers.
This is a working example tested on PHP7.3 with MariaDB 10:
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
<style>
#frm-tasks button
{
padding: 0 18px;
}
</style>
</head>
<body>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli('localhost', 'testuser', 'testpasswd', 'testdb');
$action = $_POST['action'] ?? 'list';
if(!empty($_POST["text"]))
{
$eingabe = $_POST["text"];
try
{
$stmt = $con->prepare('INSERT INTO work(text) VALUES(?)');
$stmt->bind_param('s', $_POST["text"]);
$stmt->execute();
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
if('del' === $action && isset($_POST['rows']) && is_array($_POST['rows']))
{
try{
$stmt = $con->prepare('DELETE FROM `work` WHERE `work`.`id` = ?');
$stmt->bind_param('i', $row);
foreach ($_POST['rows'] as $row)
{
$stmt->execute();
if($e = $stmt->error)
echo "<div>DB Error: $e</div>";
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
?>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<!--form action="index.php" method="post"-->
<form id="frm-tasks" action="" method="post">
<input class="lil-input" name="text" type="text">
<button type="submit" class="lil-button-green" name="action" value="add">Hinzufügen</button>
<?php
try
{
$res = $con->query('SELECT id, text FROM work');
if(0 < $res->num_rows)
{
?>
<table>
<thead>
<tr>
<th></th><th>ID</th> <th>Aufgabe</th>
</tr>
</thead>
<tbody>
<?php
while($dsatz = mysqli_fetch_object($res))
{
?>
<tr>
<td><input type="checkbox" name="rows[]" value="<?php echo $dsatz->id;?>"></td><td><?php echo $dsatz->id;?></td> <td><?php echo $dsatz->text;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<button type="submit" class="lil-button-red lil-button-small" name="action" value="del">Löschen</button>
<?php
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $e->msg;</div>";
}
?>
</form>
</div>
</div>
</div>
<!-- not needed atm script src="js/jquery-3.3.1.min.js"></script-->
<h2>POST</h2>
<?php
var_dump($_POST);
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error connecting DB: $msg;</div>";
}
?>
</body>
</html>
The key of the list is the 'th' in the database so just fixing limits
Replace
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
With
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` LIMIT 1 OFFSET ".array_search($del, mysqli_fetch_assoc($res));
mysqli_query($con, $sql2);
header("Refresh:0");
}
This question already exists:
How do I make my php not send form data to mysql if it doesn't meet criteria?
Closed 4 years ago.
As stated in the above title, I am completely perplexed as to why my site doesn't insert the data into my database (and yes I've made all the necessary columns and stuff). It is probably related to the radio buttons and the "Preke" tag so if you see anything I've messed up on, it'd help me out a lot!
Hese is my code:
<!DOCTYPE HTML>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PreErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Preke = $Pk = $Kiekis = "";
?>
<html class="no-js" lang="en">
<head>
<title>Dailės parduotuvė</title>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/stilius.css">
</head>
<body class="content ">
<div class="container">
<nav class="navbar navbar-expand-lg navbar-dark ">
<a class="navbar-brand" href="index.html">Kauno dailė</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="Visos.html">Visos prekės</a>
</li>
<li class="nav-item">
<a class="nav-link" href="Uzsakymas.php">Užsisakymas</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Kontaktai</a>
</li>
</ul>
</div>
</nav>
<div>
<div class="content sm-4 text-center">
<h2>Užsisakymo forma</h2>
<p><span class="error">* privalomi laukai</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="text-center">Vardas</p><br>
<input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<p class="text-center">Pavarde</p><br>
<input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<p class="text-center">Adresas</p><br>
<input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error">* <?php echo $AdErr;?></span><br>
Prekės rūšis:<br>
<input type="radio" name="Preke" value="Vienišas(-a)" checked>Dažai(5€)<br>
<input type="radio" name="Preke" value="Susituokęs(-usi)">Teptukas(2€)<br>
<input type="radio" name="Preke" value="Išsiskyręs(-usi)">Pieštukas(2€)<br>
<input type="radio" name="Preke" value="Našlys(-ė)">Ofiso įrankis(1€)<br>
<span class="error">* <?php echo $PreErr;?></span>
<br>
<p class="text-center">Prekės kodas</p><br>
<input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error">* <?php echo $PkErr;?></span>
<p class="text-center">Kiekis</p><br>
<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error">* <?php echo $KiekErr;?></span>
<br>
<!-- Input For Add Values To Database-->
<input type="submit" name="insert" value="Užsisakyti">
</div>
</div>
<div class="content py-5">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
}
if (empty($_POST["Preke"])) {
$PreErr = "Pasirinkite prekės tipą";
} else {
$Preke = test_input($_POST["Preke"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
//insert
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Preke = $_POST['Preke'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Preke,Pk,Kiekis,)VALUES('$Vardas','$Pavarde','$Adresas','$Preke','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</div>
<div class = "footer py-5 bg-secondary">
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
Your problem is in 'input value' properties. You set it to empty variables. Remove value from input tag like this:
<p class="text-center">Vardas</p><br><input type="text" name="Vardas" placeholder="Vardas">
it should work. About your MySQL queries, they are vulnerable for SQL Injections attack. Use PDO to protect against SQL Injections.
You have already inserted values and if you want to use values="". Then, in your SQL, you should UPDATE and not INSERT. Also,as rpm192 stated above you should use parameterized queries, otherwise you will face SQL injections. Good Luck!
I'm trying to build a comment system
this is my code
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<style>
.back_glob{width: 350px}
</style>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function(){
$( ".tombol_login" ).click(function() {
var txt = $("[name=comment]").val();
$("#comment").submit();
})});
</script>
<style>
.back_glob{width: 450px}
</style>
</head>
<body>
<div class = "back_glob">
<div class="tableC">
<img src="img\back.png" alt="back" height="42" width="42">
<div class ="back_header">
<h4>comment</h4>
</div>
<div class= "table">
<form id="comment" name="comment" action="contet2.php" method="post">
<div class="row">
<div class="col">comment</div>
<div class="col">:</div>
<div class="col"><textarea name="comment" rows ="10" cols="40"></textarea></div>
</div>
<div class="tom">
<button type="button" class="tombol_login">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
$servername = "localhost";
$dbname = "databaseform";
$username = "root";
$password = "";
session_start();
$page = 2;
$conn = new PDO("mysql:host =$servername ; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
$Comment = $_POST['comment'];
try
{
// injec
$query = "INSERT INTO comment (pkey,Comment,time,page)
VALUES (:Username,:Comment,NOW(),:page)";
$sql = $conn->prepare($query) ;
$sql->BindValue(':Username',reset($_SESSION['txt_login']));
$sql->BindValue(':Comment',$Comment);
$sql->BindValue(':page',$page);
$sql->execute();
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
echo '<div class="back_glob">';
echo '<div class = "table">';
echo '<div class = "tableC">';
echo '</div>';
}
catch(PDOException $e)
{
echo $query . "<br>" . $e->getMessage();
}
for($i = 0 ; $i < count($hasil);$i++)
{
echo'<div class="row">';
echo '<div class="col2">'.$result[$i]['Username'].'</div>';
echo '<div class="col2">'.$result[$i]['Comment'].'</div>';
echo '<div class="col2">'.$result[$i]['time'].'</div>';
echo'</div>';
}
?>
but the php part won't recognize the $_POST['comment'] before the submit button , i can't show the previous comment unless I click the submit button.
Is there any solution to correct this ??
I am really confused about your way of asking a question. I think you should have to read this tutorial of Smashing Magazine. So you can better understand of code and comment system.
I hope it will help you.
I'm using a CKEditor along with a CKFinder. Both work fine. When I browse (or copy directly) an image (or flash) to CKEditor, it's displayed within it and inserted into the MySql database.
Aafter inserting it into MySql database, I'm trying to display it in an HTML table where it isn't displayed and the alternate text is displayed.
The image path after browsing an image through the CKFinder is something like the following.
<img alt="" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style="width: 490px; height: 618px;" />
The contents inserted into the database is as follows.
<img alt="\"\"" data-cke-saved-src="\"
src="\"/ckfinder/userfiles/images/1243_SS_2502.jpg\"" st yle=&
quot;\"width:" 490px;="" height:="" 618px;\"= quot;">
Tried with htmlentities() still it doesn't work. While dealing the same with JSP using JSTL/EL, I had to do the following.
<c:out value="${str}" default="No content found." escapeXml="false"/>
escapeXml="false", where str written in EL was a java.lang.String holding the Oracle clob data after conversion.
What is the way to get around the situation in PHP? Both CKEditor and CKFinder work fine for me.
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('description', $ed_about_us);
Edit:
<?php include_once("Lock.php");?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Wagafashion</title>
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>
<link rel="stylesheet" href="css/template.css" type="text/css"/>
<!--<script type="text/javascript" language="javascript" src="ckeditor/ckeditor.js"></script>-->
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script><script>
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#dataForm").validationEngine();
});
</script>
<script language="javascript" type="text/javascript">
function deleteSingle(id)
{
var delId=confirm("About us with the id "+id+" is about to be deleted permanently.\n\nAttention : This action will never be undone!\n\nAre you sure...???");
return(delId==true?true:false);
}
</script>
</head>
<body>
<?php
include_once("Connection.php");
include_once("ckeditor/ckeditor.php");
$con=new Connection();
$con->get_connection();
$ed_about_us="";
$flag=-1;
$msg="";
if(isset($_POST['btnSubmit']))
{
$act=trim($_POST['param_action']);
$about_us=$_POST['cms_description'];
if($act=="add")
{
$res=$con->get_data("select count(*) as cnt from cms");
$cnt_cmt=mysql_result($res, 'cnt');
if($cnt_cmt==0)
{
$flag=$con->iud("insert into cms (about_us)values('".mysql_real_escape_string(urlencode($about_us))."')");
}
else
{
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."'");
}
if($flag==1)
{
$msg="Insertion done successfully.";
}
else if($flag==0)
{
$msg="Insertion failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if($act=="edit")
{
$cms_id=$_POST['cms_id'];
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."' where id=".$cms_id."");
if($flag==1)
{
$msg="About us has been updated successfully.";
}
else if($flag==0)
{
$msg="Updation failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
}
else if(isset($_GET['ed_id']))
{
$ed_res=$con->get_data("select about_us from cms where id=".$_GET['ed_id']."");
while($row=mysql_fetch_assoc($ed_res))
{
$ed_about_us=$row['about_us'];
}
}
else if(isset($_GET['del_id']))
{
$flag=$con->iud("update cms set about_us='' where id=".$_GET['del_id']);
if($flag==1)
{
$msg="About us been deleted successfully.";
}
else if($flag==0)
{
$msg="Can not delete - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if(isset($_POST['btnDelete']))
{
$set_del=$_POST['setDel'];
$flag=$con->iud("update cms set about_us='' where id in($set_del)");
$size=sizeof(split(",", $set_del));
if($flag==1)
{
if($size==1)
{
$msg="1 row deleted.";
}
else
{
$msg=$size." rows deleted.";
}
}
else if($flag==0)
{
$msg="Can not perform deletion - reason : ".mysql_errno()." : ".mysql_error();
}
}
?>
<?php include("tamplate/Template1.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate.php");?>
<?php
if($flag==1)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="green"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
else if($flag==0)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="red"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
?>
<img alt=\"\" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style=\"width: 490px; height: 618px;\" />
<!--[if !IE]>start forms<![endif]-->
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="dataForm" name="dataForm" method="post" class="search_form general_form">
<!--[if !IE]>start fieldset<![endif]-->
<fieldset>
<!--[if !IE]>start forms<![endif]-->
<div class="forms">
<!--[if !IE]>start row<![endif]-->
<div class="row">
<?php
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('cms_description', urldecode($ed_about_us));
?>
<!--[if !IE]>start row<![endif]-->
<div class="row">
<div class="buttons">
<span class="button send_form_btn"><span><span>Submit</span></span><input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" onclick="return validate();"></span>
</div>
</div>
<!--[if !IE]>end row<![endif]-->
</div>
</fieldset>
<!--[if !IE]>end fieldset<![endif]-->
<input type="hidden" id="param_action" name="param_action" value="
<?php
if(isset($_GET['ed_id']))
{
echo "edit";
}
else
{
echo "add";
}
?>
" />
<input type="hidden" id="cms_id" name="cms_id" value="<?php echo isset($_GET['ed_id'])?$_GET['ed_id']:"";?>" />
</form>
<?php include("tamplate/Template2.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate1.php");?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="mainForm" name="mainForm" method="post">
<?php include("tamplate/ExtraTemplate.php");?>
<table cellpadding="0" cellspacing="0" width="100%">
<tbody>
<th style="width: 10px;">Check</th>
<th style="width: 450px;">About Us</th>
<th style="width: 10px;">Actions</th>
<?php
$get_data=$con->get_data("select id, about_us from cms order by id");
$cnt=1;$flag='';
while($data_row=mysql_fetch_assoc($get_data))
{
extract($data_row);
$cnt%2==0?$flag="second":$flag="first";
++$cnt;
echo "<tr class='$flag'>";
echo "<td><input type='checkbox' name='chk' value='$id'></td>";
echo "<td>".urldecode($about_us)."</td>";
echo "<td><div class='actions'><ul><li><a href='".$_SERVER['PHP_SELF']."?ed_id=$id' class='action2'></a></li>";
echo "<li><a href='".$_SERVER['PHP_SELF']."?del_id=$id&table_name=cms&pri=id' onclick='return deleteSingle($id);' class='action4'></a></li></ul></div></td>";
echo "</tr>";
}
?>
</tbody>
</table>
<input type='hidden' id='setDel' name='setDel'/>
<?php include("tamplate/Template3.php");?>
</form>
<?php include("tamplate/Template4.php");?>
</body>
</html>
Did you try to use html_entity_decode() to display the contents ? It will decode the encoded html for better output. Reference here
Edit
Change your query to the following
insert into cms (about_us) values ('".mysql_real_escape_string(urlecode(stripslashes($about_us)))."')
When you get it from database it use
urldecode($value)
Where $value is the block you got from database.