I'm new to PHP, and I have stumble on the problem which I don't know how to solve. I'm 99% it is due my poor knowledge of PHP ( I'm PHP user since last Monday:) )
Just in front I will declarate that:
db conncetion is working
table does exist
values are saved correctly to the db
I have following form:
<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
<input name="live" type="checkbox" class="textfield" id="live" />
<input name="content" type="text" class="textfield" id="content" />
<input type="submit" name="Submit" value="Register" />
</form>
And following file is executing this:
<?php
//Start session
session_start();
//Include database connection details
require_once('../inc/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$live = clean($_POST['live']);
$content = clean($_POST['content']);
if(isset($live)) { $live = 1;}
if(!isset($live)) { $live = 0;}
//Create INSERT query
$qry = "INSERT INTO news(live, content) VALUES('$live','$content') ";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
echo $live."<br /><br />";
echo 'Index File';
exit();
}else {
die("Query failed");
}
?>
What the form should do:
if the checkbox is checked - save the value of '1' into field 'live' in the table 'news'
if the checkbox is NOT checked - save the value of '0'
If the checkbox has been checked everything is working fine, but if the checkbox is not checked (should echo $live = 0 ), but is displaying value = 1 and following notice: Notice: Undefined index: live in C:\wamp\www\exe\news-exec.php on line 30
Line 30: $live = clean($_POST['live']);
I'm 99% sure the problem are those declaration:
if(isset($live)) { $live = 1;}
if(!isset($live)) { $live = 0;}
What I'm doing wrong? Any suggestion much appreciated.
HTML:
<input type="hidden" name="live" class="textfield" id="live0" value="0" />
<input type="checkbox" name="live" class="textfield" id="live1" value="1" />
PHP:
$live = clean($_POST['live']);
What happens here is that when the checkbox is left unchecked, the hidden field’s value gets submitted, as-is. When the check box is checked, the hidden field’s POST value gets overwritten by the activated checkbox’s.
Hope this helps.
Try this:
if (isset($_POST['live'])) $live=1; else $live=0;
Line 30: $live = clean($_POST['live']);
causes isset($live) to be true, no matter if $_POST['live'] is set or not, so you have to check $_POST['live'] directly.
According to the HTML specs, checkboxes are not sent to the server unless they are checked. You can see the exact contents of $_POST with the var_dump() function.
There are many ways to deal with this. Since you are not assigning a value attribute, I guess the value is irrelevant so you can do this:
// $live is now a boolean
$live = isset($_POST['live']);
First of all you don't need to clean a variable that's existance is used as a flag. You get the error message because in the case the checkbox is not checked $_POST['live'] doesn't even exist.
$live = (isset($_POST['live']))?1:0;
Should indeed do the trick. Just for some practice with the ternary operator.
When you don't check the checkbox, $_POST["live"] is not set, that's why you get the error.
You should try something like:
$live = isset($_POST["live"]) ? 1 : 0;
To check Checkbox checked or not do the following :
<input name="live" type="checkbox" class="textfield" id="live" value="Yes" />
if(isset($_POST['live']) && $_POST['live'] == 'Yes')
{
$live = 1;
}
else
{
$live = 0;
}
and check the query
<input name="live" type="checkbox" value="Yes" class="textfield" id="live" />
if(isset($live) && $live == 'Yes'){
$live = 1;
}else{
$live = 0;
}
As well as the examples given here, you might want to check the data type you've set on the DB column for "live". You're passing it as a string, but if you've set it as an INT you don't need the quotes around the value in the INSERT
$qry = "INSERT INTO news(live, content) VALUES($live,'$content') ";
Same with PDO
<?php
//Start session
session_start();
//Include database connection details
require_once('../inc/config.php');
/*** pdo connect ***/
$dbh = new PDO("mysql:host=$hostname;dbname=YOURDB", $username, $password);
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("INSERT INTO news(live, content) VALUES(:checkbox,:textbox)");
if(isset($_POST)){
$live = $_POST['live'];
$content = $_POST['content'];
try {
/*** bind the paramaters ***/
$stmt->bindParam(':checkbox', $live, PDO::PARAM_INT);
$stmt->bindParam(':textbox', $content);
/*** execute the prepared statement ***/
$stmt->execute();
echo "Query successful ".$live."<br /><br />";
echo 'Index File';
}catch(PDOException $e){
die("Query failed");
}
}else{
?>
<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
<input name="live" type="checkbox" value="1" class="textfield" id="live" />
<input name="content" type="text" value="" class="textfield" id="content" />
<input type="submit" name="Submit" value="Register" />
</form>
<?php
}
/*db finnish*/
$dbh = null;
?>
Related
I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?
This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";
I am having some trouble trying to delete a member from the database I'm using, I don't think it is getting the Username correctly. Here is the form I am using for HTML
deleteForm.php
<?php
//begin our session
session_start();
?>
<html>
<head>
<title>Welcome</title>
</head>
<form action="deleteUser.php">
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
</form>
</body>
</html>
And this is the code to handle the deletion itself:
deleteUser.php
<?php
//begin our session
session_start();
//Check if username, password have been sent
if((!filter_input(INPUT_POST, 'Username')))
{
echo 'Please enter a valid username';
}
else
{
//Enter the valid data into the database
$memberUsername = filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_STRING);
echo $memberUsername;
$SQLhostname = "****";
$SQLusername = "****";
$SQLpassword = "****";
$databaseName = "****";
try
{
echo "in the try block";
// Create connection
$conn = mysqli_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect MySQL");
$db_selected = mysqli_select_db($conn, $databaseName)
or die("Could not select database");
$deleteMember = "DELETE FROM customers
WHERE name =
'$memberUsername'";
$result = $conn->query($deleteMember);
if(! $result ){
die('Could not delete member: ' . $conn->error);}
else{
echo "Member deleted <br/>";
}
mysqli_close($conn);
}
catch (Exception $ex)
{
//To be added
}
}
?>
The problem is it always enters the if statement and asks for a valid username which I'm assuming is not being set.
Add method attribute to your form.
<form action="deleteUser.php" method="post">
<!--^^^^^^^^^^-->
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
Just as a quick FYI:
Whenever a method is omitted in a form, it defaults to GET and you're using INPUT_POST therefore you should either be using INPUT_GET or add a post method, i.e: method="post".
Consult the manual:
http://php.net/manual/en/function.filter-input.php
Plus, and for your added safety, your code is open SQL injection. Do use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
in the form tag add "method" attribute:
<form ... method="POST">
In the PHP script you van find the value of inputs in the variable $_GET:
$_GET[Username'']
Kevin
I've spent the last day trying to figure out how to incorporate PDO into my code to prevent sql injections. This is what I have come up with. However, whenever I submit my information from the browser, it is not updated into my table and no error messages are shown. Something is wrong but I'm not sure what. I'm postive the syntax is not the problem because I've checked that multiple times. I know my database can be accessed so I'm thinking there is a problem with the way I'm using PDO. Please help me guys.
The PSBE_LOGIN contains all the information to access my database
<?php
require_once 'PSBE_LOGIN.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL:" . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database:" . mysql_error());
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
?>
EDIT: CODE REWRITTEN TO INCLUDE PDO API.
<?php
require_once'connection.php';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>
Get rid of both
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
and
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
because the function you're using is based on an mysql_ function and those two APIs do not mix.
You don't need it, because you're already using placeholders.
while replacing it with
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
You also need to change
$stmt = $pdo->prepare(...
to
$stmt = $db->prepare(...
given your PDO connection $db = new PDO(...
You are not using them correctly. You need to connect using the PDO API (you're connecting using the mysql_ API). Otherwise, the preparation is correct.
I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly