How to validate if a checkbox is checked in PHP [duplicate] - php

This question already has answers here:
How to validate a single checkbox using PHP & MySQL
(2 answers)
How to validate checkbox group in PHP [closed]
(2 answers)
PHP Checkbox array validating
(4 answers)
How to validate a checkbox input using PHP?
(4 answers)
Closed 5 years ago.
I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation checkbox.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
echo "<input type='checkbox' name='feeling' value='good'>Show translation";
echo "<br><br>";
}
$conn->close();
?>
</body>
</html>
Everything works fine except that I don't know how to show the translation of the word when the checkbox is checked.
Do you have any suggestions of how to let that work?
Thanks

Related

writing in a mysql table using POST & php

I'm trying to register the e-mail entered in my form by users in my SQL table. but I'm not receiving any errors and the data are not saved either!
<?php
echo "I was here !!!";
if(!empty($_POST['mail']))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mailing";
echo "I was here !!!";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO contact VALUES ("","'.$_POST['mail'].'")';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
and my html code:
<div class="form">
<p>Rester notifié par toutes les nouveautés !</p>
<form method="post" action="index.php" class="mainform">
<div class="field"><input type="text" class="field" name="mail" /></div>
<div class="submit"><input class="submit" type="button" value="Envoyer" /></div>
</form>
</div>
can you tell me what's the problem ?
change your button type .because if you want to submit the data by form then button type should be submit like that
<input class="submit" type="submit" value="Envoyer" />
Check if there's a value for $_POST['mail']. Your condition didn't handle empty value for $_POST['mail']. If there is a value. Change your query
INSERT INTO contact(email) VALUES ("'.$_POST['mail'].'")
Try this. Since you only need to add an email. Hope it helps.

how to return values from mysql table with ajax and php

I am new to programing. I have one form to create Groups. It has two text fields Code Id and Code description. After submitting it showed me that the Code Id which i entered is already exist and if not it add one record in MySQL table. What I want that when I leave the Id text field at the same time with onchange event and Ajax to search table and alert if the Id already exit and at the same time fill name text box with description of that Code Id. How to do that? My code is
HTML file
...
</style>
<body>
<H1>Create Grup</h1>
<br>
<form action="creategrup.php" method="post">
<p>
<label for="codigo">Grup Id:</label>
<input type="text" required="required" autofocus="autofocus"
maxlength="4" name="codigo" id="codigo">
</p>
<p>
<label for="nombre">Grupo description:</label>
<input type="text" required="required" name="nombre" id="nombre"">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
And PHP is
<?php
include 'connectdb.php';
$nombre=$_POST['nombre'];
$codigo=$_POST['codigo'];
$sql = "select codigogrupo,nombregrupo from grupo where
codigogrupo='$codigo'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) >0) {
echo "<p><h1><b>Grup Id $codigo allready exist....</h1></b></p><br>";
echo "<a href='creategrup.html'>Go Back</a>";
}
else {
mysqli_query($conn, "insert into grupo(codigogrupo,nombregrupo)
values('$codigo','$nombre')");
if(mysqli_affected_rows($conn)>0){
echo "<p><h1><b>Grup $nombre added</h1></b></p>";
echo "<a href='creategrup.html'>Go Back</a>";
} else {
echo "Grup not added<br>";
echo mysqli_error ($conn);
}
}
?>
Connectdb.php
<?php
$servername = "server name";
$username = "user name";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
?>
Please help me.
You are getting already exist message so that may be confirm that there is another data with same id. For further assistance please knock me

PHP redirect failing [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 5 years ago.
I know this is a commonly asked question, however I've checked for white space, checked the encoding of the files and I can't work this out.
When I submit this form it should redirect back to 'successful_login.php' however it doesn't it just stays on the same page.
available_update.php
<?php
include 'credentials.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ID=$_POST['ID'];
$available=$_POST['available'];
$sql = "UPDATE users SET available='$available' WHERE ID='$ID'";
if ($conn->query($sql) === TRUE) {
header("http://www.jtsanderson.co.uk/users/successful_login.php");
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
credentials.php
<?php
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
?>
HTML Form
<div class="w3-half">
<form action="availableupdate.php" method="post" id="available">
<input type="hidden" name="ID" value="<?php echo $userData['id'] ?>">
<input type="hidden" name="available" value="Yes">
</form>
<button type="submit" form="available" name="signupSubmit"
class="w3-button w3-block w3-green w3-section" title="Accept"><i class="fa fa-check"></i></button>
</div>
You are using header() incorrectly.
You need to change
header("http://www.jtsanderson.co.uk/users/successful_login.php");
to
header("Location: http://www.jtsanderson.co.uk/users/successful_login.php");

Apostrophe in HTML textarea causing PHP error [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
This is my first ever post on Stack Overflow. I have had a good try with this and a good search for answers, but to no avail. So here goes:
I have made a basic messaging app just for coding practice. Obviously, I want it to be safe from xss so have used "HTMLspecialchars".
The problem:
The app works fine as long as no one puts an apostrophe in the message. So the message "Let's go" throws an error:
let's go Error:INSERT INTO chat (msg) VALUES ('Hello let's go')
You have an error in your SQL syntax; check the manual that corresponds to your >MariaDB server version for the right syntax to use near 's go')' at line 2
Here's my code for inputting and sending to mysql:
<!DOCTYPE html>
<!-- input -->
<html>
<body>
<?php
// define variables and set to empty values
$name = $msg = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$msg = test_input($_POST["msg"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Messaging Appq</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value ="<?php echo htmlspecialchars($_POST['name']); ?> ">
<br><br>
Message: <textarea name="msg" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<!-- enter on DB -->
<?php
$servername = "localhost";
$username = "*********";
$password = "*********";
$dbname = "***********";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
$msg=$_POST['msg'];
$bothd = $name . $msg;
$sql = "INSERT INTO chat (msg)
VALUES ('$bothd')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error:" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
So, I know i need to use "ent_quotes". But where should it go? I see the normal syntax is
<?php echo htmlspecialchars($str, ENT_QUOTES); ?>
and I have tried putting "ent_quotes" in the following positions, obviously not all at the same time:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES);?>">
Name: <input type="text" name="name" value ="<?php echo htmlspecialchars($_POST['name'], ENT_QUOTES); ?> ">
<br><br>
Message: <textarea name="msg" rows="5" cols="40" value ="<?php echo htmlspecialchars($msg, ENT_QUOTES); ?>"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
I also tried adding it to the function:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
Apologies if I am missing something obvious! I am relatively new to this!
SELECT 'A ''quoted'' word.' AS text FROM DUAL;
TEXT
A 'quoted' word.
you have to edit the query string and add another ' to your string

Display data from database in HTML page [duplicate]

This question already has an answer here:
Show data pulled from database, based on html form input and display in html page
(1 answer)
Closed 6 years ago.
I would like to display data from my database on page load, but I don't know how and I didn't found any functional way. Inserting works fine.
Here is my HTML code for data inserting:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="snapname">Name:</label>
<input type="text" name="snapname">
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age">
</p>
<input type="submit" value="odeslat">
</form>
</body>
</html>
PHP for connect and insert data to database:
<?php
$servername = "localhost";
$username = "admin";
$password = "***";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Could not connect to server: " . $conn->connect_error);
}
$first_name = mysqli_real_escape_string($conn, $_POST['snapname']);
$last_name = mysqli_real_escape_string($conn, $_POST['age']);
$Jmeno = $_POST['snapname'];
$Vek = $_POST['age'];
$sql = "INSERT INTO snapy (ID, username, age, date)
VALUES (0, '$Jmeno', '$Vek', CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Can someone help me with displaying data in HTML file?
You need to run a SELECT-request. Since you are using MySQLi you want to use something like:
$sql = "SELECT * FROM snapy";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["age"]. " yo<br>";
}
} else {
echo "0 results";
}
Found here: http://www.w3schools.com/php/php_mysql_select.asp

Categories