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 '<a href="../">Index File</a>';
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.
echo "<pre>"; var_dump($variable); echo "</pre>";to print out variable values at different places in code. You will find the answer fast.if(!isset($live)) { $live = 0;}work with this?