How to save checkbox value to MySQL database? - php

I have following html:
<label for="live">Live</label>
<input type="checkbox" name="live" id="live" />
How to save text value of selected = '1'/ or text value of unchecked = '0' to database using SQL INSERT?
Any suggestion much appreciated.
PHP handling the html form (at the moment 'live' is an input):
<?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());
}
if($link) {
echo "DB SUCESS <br />";
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
if($db){ echo "TABLE SUCCESS<br />"; }
//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']);
//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) {
//header("location: ../form/register-success.php");
echo "Succes";
exit();
}else {
die("Query failed");
}
?>

<input type="checkbox" name="live" value="1" />Live<br />
^Note the Value "1". If someone checks the box, it will be a 1, if they don't it will be NULL. (NOT 0!)
Do an isset on the next page, if it's set, you're good to go, if it's not, just set it to zero.
if (!isset($live)) $live = 0;

Only checked HTML checkboxes send values in the response. Use isset.

Related

I GET "No database selected" ERROR even that is selected

Im new in MySql and PHP and im trying to make a CRUD but everytime i try to insert data into table called "studenti" i get the error that i didnt select a database but i selected a database with mysqli_select_db($con, "d_base");
Somebody please help me cuz i dont understand why its not workin'
Here is the code;
$id = $_POST['ID'];
$nota = $_POST['Nota'];
$emri = $_POST['Emri'];
$mbiemri = $_POST['Mbiemri'];
$servername = "localhost";
$dbname = "d_base";
// 1.Create connection
$con = mysqli_connect("localhost","d_base");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')"))
{
echo("Error description: " . mysqli_error($con));
}
// Perform queries
mysqli_select_db($con, "d_base");
mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')");
mysqli_close($con);
Before all that if you are a begginer go straight on PDO or use mysqli with prepared statements its safer.
Here is example how your php and html form must look like and work.
First you must check if submit button is pressed, if its pressed read values form form $_POST variables.
Second thing you must escape injection to your mysql by using function mysqli_real_escape_string().
After that try to insert query and check for error, if there is no error query will be inserted successfully.
PHP code
<?php
// set error report ; 1 = on | 0 = off
error_reporting(1);
$db_host = "localhost"; // host
$db_user = "root"; // database username
$db_pass = ""; // database password
$db_name = "d_base"; // database name
// 1.Create connection
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// if form is submited
if (isset($_POST['submit']))
{
// escape post variables
$id = mysqli_real_escape_string($con, $_POST['ID']);
$nota = mysqli_real_escape_string($con, $_POST['Nota']);
$emri = mysqli_real_escape_string($con, $_POST['Emri']);
$mbiemri = mysqli_real_escape_string($con, $_POST['Mbiemri']);
// make query
$query = mysqli_query($con, "INSERT INTO studenti (id, nota, emri, mbiemri VALUES ('$id', '$nota', '$emri', '$mbiemri')")
// check for query
if (!$query)
{
echo "Error description: " . mysqli_error($con);
}
else
{
echo "Query inserted.";
}
// close connenction
mysqli_close($con);
}
?>
<form action="" method="post">
<input type="text" name="ID" placeholder="Id"><br />
<input type="text" name="Nota" placeholder="Nota"><br />
<input type="text" name="Emri" placeholder="Emri"><br />
<input type="text" name="Mbiemri" placeholder="Mbiemri"><br />
<input type="submit" name="submit" value="Submit form">
</form>

display user input as comment on same page

I'm trying to create a comment system on my webpage. I want the user to be able in input a comment and have it automatically display on the same page, and reload so that if another user wants to comment the previous comment will also be there. So far, I have created a database that takes in the comments. I have tried to display the comments by querying through my database and printing it out, but it just seems to crash my site.
This is the code I have so far
index.php:
<form action="insert.php" method="GET">
Comments:
<input type="text" name="field1_name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
$query="SELECT COMMENTS FROM parentComment";
$results = mysqli_query($query);
while ($row = mysqli_fetch_assoc($results)) {
echo $row['COMMENTS'];
}
?>
insert.php:
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'x'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$field1_name')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if ($result) {
//echo $_GET["field1_name"];
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
So far everything works as in the comments are being inserted into the database. My problem is with retrieving the comments and displaying it to the user on the same page. I've tried to do so, but it seems to be not working. Not sure where I'm going wrong in my implementation (I've implemented it in the index.php file)
You didn't connect to your db for the query:
$results = mysqli_query($query);
Pass the connection to the query:
$results = mysqli_query($link, $query);
It's required.
http://php.net/manual/en/mysqli.query.php
You also need to make sure that you did establish a connection in that file, otherwise it won't work.

Inserting user updates into SQL with PHP

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//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
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>
Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"
First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

Pulling multiple fields from database using forms and php

I have a database with multiple rows with various fields.
I have a form that contains a drop down list.
The drop down list displays one of the database fields (field_name) for each row in the database.
When the user selects the desired entry hits SUBMIT, that value is passed to the results.php page and can be used via $_POST.
All of this currently works.
I would like a way to send the rest of the row's fields that correspond to the row of the selected field (not just the "field_name") from the database along with what is selected from the drop down menu.
For instance, if I have a database with rows with a fields named "name", "date", and "age", I would like to have all the database rows "name"s appear in the drop down list and once submitted, pass that particular name's "date" and "age" on to the results.php for use on that page.
<html>
<head>
<title>Drop Down Test</title>
</head>
<body style="font-family: verdana; font-size: 11px;">
<?php
//Variables for connecting to database.
$hostname = "abcd";
$username = "abcd";
$dbname = "abcd";
$password = "abcd";
$usertable = "abcd";
//Connecting to database
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
$query = "SELECT * FROM abcd";
$result = mysql_query($query) or die(mysql_error());
?>
<h2>Drop Down Test Form</h2>
<p>Please fill out the form below and click submit.</p>
<form action="results.php" method="POST">
<p>Drop Down Test:
<select name='event'>
<!-- Drop down -->
<?php
while($row = mysql_fetch_array($result))
{
echo '<option>' . $row['field_name']. '</option>';
}
?>
</select>
<p><input type="submit" value="Submit"><p>
</form>
you should put a value on your option like this:
echo '<option value = "'.$row['field_name'].'" name = "">' . $row['field_name']. '</option>';
then you can access it by $_POST['event'];
UPDATE
getting all the values from the select, you can use $_SESSION variables to pass it to the other php.file.
// First of all, I advice you to connect via PDO, or at least msqli, because mysql_query is depreciated.
// To connect with database you need:
DEFINE("USER", "root");
DEFINE("DBNAME", "test");
DEFINE("DBPASSWORD", "");
DEFINE("DBHOST", "localhost");
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME,USER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//The query:
$sth = $dbh->prepare("SELECT name,age,date FROM test");
$sth->execute();
//the drop down form
echo '<form action="results.php" method="POST">
<select name="event"><option value=0></option>';
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) { extract($result);
echo '<option value="date:'.$date.'-age:'.$age.'"/>'.$name.'</option>';
echo '</select>
<p><input type="submit" value="Submit"><p>
</form>';
}
//the event in the records.php by clicking submit
if(isset($_POST['event'])){
echo 'name:',$name'-date:',$date,'-$age',$age;
}
This did the trick (in results.php):
<?php
$hostname = "****";
$username = "****";
$dbname = "****";
$password = "****";
$usertable = "abcd";
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
//it was this SQL query that was the key, namely the WHERE statement
$query = "SELECT * from abcd where field_name='$_POST[event]'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo "id: " . $row[0] . "<br/>";
echo "field_name: " . $row[1] . "<br/>";
//etc...
//try to throw the individual results into variables
$variable = $row[1];
echo "Check to see that the variable was passed a value: " . $variable . "<br />";
echo "Check to see that form selection carried over: " . $_POST['event'] . "<br />";
?>
I realize this is not the "up-to-date" way of doing things and I will now try to get everything "modernized".
Thanks for all the help!

HTML Button to Update Mysql table

I am trying to UPDATE a row from a MySQL Table with a button in my html page. When i press the button it outputs "Query failed". What should I change to make it work ?
My Html Code:
<form action="status1.php">
<input type="submit" name="approve" value=" + ">
</form>
My Php Code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="UPDATE applications SET (status) values('1') WHERE today='$today'";
$result = mysql_query($qry);
if($result) {
header("location: applications-admin.php");
exit();
}else {
die("Query failed");
}
?>
You're using the wrong syntax for an UPDATE; it should be something like this:
$qry="UPDATE applications SET status='1' WHERE today='$today'";
HOWEVER
You should look at moving away from the mysql_* functions, as they're being deprecated - you should look at using PDO or mysqli instead.
UPDATE tablename SET fieldname=value WHERE [conditions]

Categories