Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.
Thank you!
if($_SESSION['loginSuccess']==1) {
// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "<div id=\"draggable\" class=\"ui-widget-content\"><table border='5'><tr class=\"ui-widget-header\"><td><u>Task Name:</u></td><td><u>Class:</u></td><td><u>Due Date:</u></td><td><u>Task Type:</u></td></tr>";
echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];
$class = $row[2];
$taskDueDate = $row[3];
$taskType = $row[4];
echo "<tr><td>'$taskName'</td><td>'$class'</td><td>'$taskDueDate'</td><td>'$taskType'</td></tr>";
}
echo "</table>";
function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}
if($_POST['taskName'] != NULL) {
addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}
?>
<!-- <img border="1" alt="New" src="/newTask.png" id="newTask" onmouseClick="showTaskField"/> -->
<p><form name="newTask" method="post" action="index.php" id="newTask"><br>
Task Name: <input name="taskName" type="text"> (necessary)<br>
Class: <input name="class" type="text"><Br>
Due Date: <input name="dueDate" type="text" id="datepicker"><Br>
Type:
<input type="submit"></p></div>
Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().
Related
I am trying to figure out mysqli (I am just a starting scripter). I created the following script to grab 3 different values from my database. And it prints it on the screen in different textareas and input fields.
What I want to be able to do is when I press the update button that it'll update the records in the database for the form where the button is attached to.
Can anyone give me some tips on how to achieve something like that?
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$standaardtekstlabel = $mysqli->query("SELECT standaardtekst_label FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardtekstnl = $mysqli->query("SELECT standaardtekst_tekst FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardteksten = $mysqli->query("SELECT standaardtekst_tekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$label_Tekst = mysqli_fetch_row($standaardtekstlabel);
$EN_Tekst = mysqli_fetch_row($standaardteksten);
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $label_Tekst[0] . '>
<textarea name="standaardtekst_tekst">' . $NL_Tekst[0] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $EN_Tekst[0] . '</textarea>
<input type="submit" value="update">
</form>';
}
?>
First of all, there is absolutely 0.0 reason why you're using 3 queries for the information you're trying to get. You can simply have: $standaardtekst = $mysqli->query("SELECT standaardtekst_label,standaardtekst_tekst,standaardtekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
Now regarding your question that is now probably obsolete:
Make the names of the input like this: standaardtekst_tekst[] saving it in an array.
You also need to have a unique(auto increment) key in your database like: id and put it in every form. You can even use the value of this field in the name like this: standaardtekst_tekst[$id].
You could edit your code a bit to look something like this:
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$q = $mysqli->query("SELECT standaardtekst_id, standaardtekst_label,
standaardtekst_tekst, standaard_tekst_tekst_en
FROM Standaardteksten
WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$row = mysqli_fetch_row($q);
?>
<form action="" method="POST">
<input type="text" name="formData[<?= $row['id']; ?>][standaardtekst_label]" value="<?= $row['standaardtekst_label']; ?>">
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst]"><?= $row['standaardtekst_tekst']; ?></textarea>
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst_en]"><?= $row['standaardtekst_tekst_en']; ?></textarea>
<input type="submit" value="update">
</form>
<?php
}
?>
What I've done:
Made your 3 queries into a single query
Gave each form a unique id
Cleaned up the code a bit
This enables you to do the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formData'])) {
foreach ($_POST['formData'] as $id => $value) {
$stmt = $mysqli->query("UPDATE standaardtekst SET standaardtekst_label='".$value['standaadtekst_label']."', standaardtekst_tekst='".$value['standaardtekst_tekst']."', standaardtekst_tekst_en='".$value['standaardtekst_tekst_en']."' WHERE standaardtekst_id='".$id."'");
}
}
Thx for the help everyone. Everything is working right now.
This is the script i used to get it to work :-)
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$result = $mysqli->query("SELECT * FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$row_s = $result->fetch_assoc();
do{
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $row_s['standaardtekst_label'] . '>
<textarea name="standaardtekst_tekst">' . $row_s['standaardtekst_tekst'] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $row_s['standaardtekst_tekst_en'] . '</textarea>
<input type="text" name="standaardtekst_ID" value="'. $row_s['standaardtekst_ID'] .'"/>
<input type="submit" value="update">
</form>';
} while($row_s = $result->fetch_assoc());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['standaardtekst_ID']))
{
$updatesql= sprintf("UPDATE Standaardteksten SET standaardtekst_label='%s', standaardtekst_tekst='%s', standaardtekst_tekst_en='%s' WHERE standaardtekst_ID='%s'",
$_POST[standaardtekst_label],
$_POST[standaardtekst_tekst],
$_POST[standaardtekst_tekst_en],
$_POST[standaardtekst_ID]
);
$mysqli->query($updatesql);
echo "Het volgende wordt aangepast: <br />", "Label:", $_POST[standaardtekst_label], "<br />" , "NL tekst:", $_POST[standaardtekst_tekst], "<br />" , "EN tekst:", $_POST[standaardtekst_tekst_en];
echo "<meta http-equiv='refresh' content='1;url=/form.php'>";
}
?>
My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}
after trying to debug this snipet of code for hours, I find I cannot figure out why my edit form wont update for the life of me. I'm not sure if it's because I'm not using GET or POST methods correctly, I'm mis-using mysql, or a combination of the both. I cant even figure out why a line of print "hi"; wont show up. if i take out the line of code testing when the edit submit button is hit the print lines come out but my database wont update. So I figure I'm stuck where I can't do anymore print line debugging untill I figure out what I'm doing wrong. here is my code.. I commented next to the "print "hi";" line that doesnt show up. keep in mind I'm pretty sure I tried every combination of GET and POST and it still doesnt show up...
<html lang="en">
<head>
<title>Employee</title>
</head>
<body>
Clean <br>
<form method="post" action="employ.php">
<input type="text" name="fname">First Name<br>
<input type="text" name="lname">Last Name<br>
<input type="text" name="email">email<br>
<input type="text" name="zip">zip code<br>
<input type="submit" name="add" value="Add"> <!-- button itself -->
</form>
<br>
<?php //server login name password database
$link = mysqli_connect("server", "login", "password", "database") or die(mysqli_error());
if(isset($_POST['add'])) //this processes after user submits data.
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
$querycheck = "select * from employees where fname='$fname' and email='$email'";
$resultcheck = mysqli_query($link, $querycheck); //link query to database
if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
{//if not process the insert query
$query = "insert into employees values('', '$fname', '$lname', '$email', '$zip')";
mysqli_query($link, $query); //link query to database
print "Employee Added"; // print confirmation
}
else
{
print "That record already exists!";
}
}
else
{
print "You did not fill out the form correctly!";
}
} ////////////////////////////////edit portion/////////////////////////////
if(isset($_GET['edit']))
{
print "teseting edit<br><br>";
?>
<form method="get" action="employ.php">
<input type="text" name="fname" value = "<?php echo $_GET['fname']?>">First Name<br>
<input type="text" name="lname" value = "<?php echo $_GET['lname']?>">Last Name<br>
<input type="text" name="email" value = "<?php echo $_GET['email']?>">email<br>
<input type="text" name="zip" value = "<?php echo $_GET['zip']?>">zip code<br>
<input type="hidden" name="employeeid" value = "<?php echo $_GET['employeeid']?>">
<input type="submit" name="endedit" value="Edit"> <!-- button itself -->
</form>
<?php
print "teseting end edit <br><br>";
if(isset($_POST['endedit'])) //this processes after user submits edited data
{ //tried get and post
print "hi"; // DOESNT APPEAR
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$employeeidtemp = $_POST['employeeid'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
//$querycheck = "select * from employees where employeeid='$employeeidtemp'";
//$resultcheck = mysqli_query($link, $querycheck); //link query to database
// if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
// {
$query = "UPDATE employees SET fname='$fname', lname='$lname', email='$email', zip='$zip' WHERE employeeid='$employeeidtemp'";
mysqli_query($link, $query); //link query to database
print "Employee Updated"; // print confirmation
// }
// else
// print "huh?";
}
else
{
print "You did not fill out the form correctly!";
}
}
}
if(isset($_GET['delete']))
{
print "teseting delete<br><br>";
}
showemp();
function showemp()
{
global $link;
if(isset($_GET['choice']))
{
$choice = $_GET['choice'];
}
else
{
$choice = "lname";
}
$query = "select * from employees order by $choice";
$result = mysqli_query($link, $query);
// print table (happens first before input)
// first print row of links/headers that sort
print "<table border='1'>
<tr>
<th>Edit</th>
<th>Delete</th>
<th><a href='employ.php?choice=fname'>FNAME</a></th>
<th><a href='employ.php?choice=lname'>LNAME</a></th>
<th><a href='employ.php?choice=email'>EMAIL</a></th>
<th><a href='employ.php?choice=zip'>ZIP</a></th>
</tr>";
//while the next row (set by query) exists?
while($row = mysqli_fetch_row($result))
{
list($employeeid, $fname, $lname, $email, $zip) = $row;
print "<tr>
<td><a href='employ.php?edit=yes&employeeid=$employeeid&fname=$fname&lname=$lname&email=$email&zip=$zip'>Edit</a></td>
<td><a href='employ.php?delete=yes&employeeid=$employeeid
onclick='return confirm(\"Are you sure\")'>Delete</a></td>
<td>$fname</td>
<td>$lname</td>
<td>$email</td>
<td>$zip</td>
</tr>";
}
print "</table>";
}
?>
</body>
</html>
You have several errors:
You do not check the result of queries, use at least
code mysqli_query($link, $query) or die(mysqli_error($link));
When I kick your code with checking errors, I found that adding query does not work - your empty string value for employeeid does not accepted for my integer field.
Do not use GET in forms. Always POST. If you need reaction on GET-url, write it separately or use $_REQUEST var.
In INSERT query always write fields. When you will decide to change list of fields in mysql table, then you can get the strange behavior of this code.
Your main error is that your condition with print 'hi' is inside the condition if(isset($_GET['edit'])), it does not work when user sublim form.
again I'm trying to study php mysql and it seems that I tried everything thing to figure the problem out.. but it seems as a beginner codes in the internet are not helping.. I really can't update the records in the database.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("dbtry",$db);
$id = isset($_GET['id']) ? $_GET['id'] : null;
$submit = isset($_POST['submit']);
if ($id) {
if ($submit) {
$result = mysql_query("select * from employees where id = " . mysql_real_escape_string($_GET['id']) );
$row = mysql_num_rows($result);
if ($myrow != 0) {
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
}
echo "Thank you! Information updated.\n";
} else {
// query the DB
$result = mysql_query("SELECT * FROM `employees` WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="first" value="<?php echo $myrow["firstname"] ?>"><br>
Last name:<input type="Text" name="last" value="<?php echo $myrow["lastname"] ?>"><br>
Address:<input type="Text" name="address" value="<?php echo $myrow["address"]
?>"><br>
Position:<input type="Text" name="position" value="<?php echo $myrow["position"]
?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
} else {
// display list of employees
$result = mysql_query("SELECT * FROM employees",$db);
while ($myrow = mysql_fetch_array($result)) {
printf("%s %s<br>\n", $_SERVER['PHP_SELF'], $myrow["id"],
$myrow["firstname"], $myrow["lastname"]);
}
}
?>
</body>
</html>
There are two things potentially causing you a problem: firstly, the values you are trying to set are variables which have not been defined. I'm assuming the begginers code you found assumed you had register globals enabled, you really don't want to do this!
The second problem, is that if you do have register globals enabled, the data isn't being sanitized, so a quotation mark could send the update awry.
Try this instead:
$first = mysql_real_escape_string( $_POST['first'] );
$last = mysql_real_escape_string( $_POST['last'] );
$address= mysql_real_escape_string( $_POST['address'] );
$position = mysql_real_escape_string( $_POST['position'] );
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
This should at least get you up and running. I'd strongly advise that you use either the MySQLi library, or PHP PDO, and think about using prepared statements for added security.
mysql_query("UPDATE `employees` SET `firstname`='".$first."', `lastname`='".$last."',
`address`='".$address."', `position`='".$position."' WHERE `id` = '".$id".' ; ", $db) or
die(mysql_error());
I think the problem may lie in your connection to the database. The third parameter of the mysql_connect function is a password. Therefore this:
$db = mysql_connect("localhost", "root");
should be:
$db = mysql_connect("localhost", "root", "yourPassword");
It would also help a lot if you posted what type of error you are getting.
You need to differentiate post and get. Follow the working example below. It will sort you out :D
<html>
<body>
<?php
$db = mysql_connect("localhost", "root","");
mysql_select_db("test",$db);
if($_SERVER['REQUEST_METHOD']=='POST')
{
//SUBMIT FORM
$id=isset($_POST['id'])?$_POST['id']:0;
if ($id) {
$result = mysql_query("select * from parameter where id = " . mysql_real_escape_string($id) );
$rows = mysql_num_rows($result);
if ($rows != 0) {
mysql_query ("UPDATE parameter SET name='".$_POST['name']."',value='".$_POST['value']."' WHERE id = '".$id."'");
echo "Thank you! Information updated.\n";
}
}
}
if($_SERVER['REQUEST_METHOD']=='GET')
{
//SELECT WHERE ID=GER VAR AND DISPLAY
$id = isset($_GET['id']) ? $_GET['id'] :0;//
if ($id) {
// query the DB
$result = mysql_query("SELECT * FROM parameter WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="name" value="<?php echo $myrow["name"] ?>"><br>
Last name:<input type="Text" name="value" value="<?php echo $myrow["value"] ?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
else {
// display list of employees
$result = mysql_query("SELECT * FROM parameter",$db);
while ($myrow = mysql_fetch_array($result)) {
echo "<a href='".$_SERVER['PHP_SELF']."?id=".$myrow['id']."'>".$myrow['name'].": ".$myrow['value']."</a><br>";
}
}
}
?>
</body>
</html>
Usually when I run into this problem, it's because auto commit is off and I forgot to tell the connection explicitly to commit.
EDIT: Have you tried this: How can I implement commit/rollback for MySQL in PHP?? Depending on your settings, InnoDB can be set to auto commit off, which means you need to tell MySQL explicitly to commit updates after your done.
i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...