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){
...
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'>";
}
?>
I have a form which sends a Roll_No value using post method to a php file:
//Query the database
$resultSet = $mysqli->query("SELECT * FROM late WHERE 'Roll_No' LIKE '" . $_POST['Roll_No'] . "';");
//Count the returned rows
if($resultSet->num_rows != 0){
//Turn the results into an array and echo them
while($rows = $resultSet->fetch_assoc())
{
$Roll_No = $rows['Roll_No'];
$Time = $rows['Time'];
echo "<p>Roll_No: $Roll_No <br />Time: $Time</p>";
}
My code seems to be unable to take the Roll_No value from the form and therefore gives no results.
EDIT: Here's the form
<form action="report-d1.php" method="post" />
<p>Search by Roll_No<input type="text" name="Roll_No" /></p>
<input type="submit" value="Submit" />
</form>
I have some Problems with the following code.
The hidden field is not posted to the next page.
I have tried to put it next to the option field, but that creates some different problems like duplicating the dropdownmenue.
can anyone help me please?
<?php
$dbhost = 'localhost';
$dbuser = '-----';
$dbpass = '-----';
$db = '-----';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
$query = "SELECT * FROM Eintraege"; $result = mysql_query($query);
?>
<form action="deletescript.php" method="post">
<select name="loeschen">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ID'];?>"><?php echo $line['Titel'];?></option>
<?php
}
?>
</select>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="hidden" name="titel" value="<?php echo $line['Titel'];?>" />
<?php
}
?>
Vorname <br /><input type="text" name="name" value="" class="text" /><br /><br />
Name <br /><input type="text" name="vorname" value="" class="text" /><br /><br />
Email <br /><input type="text" name="email" value="" class="text" /><br /><br />
<input type="submit" name="submit" />
</form>
You should at least use mysqli, making sure you have the connection on a secure page like:
// connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You have a couple of other problems too.
1) Since mysql_fetch_array() always returns the next row of results, when mysql_fetch_array() is called again in your second while loop, $line is falsey, because there are no more rows to fetch, so the loop does not run. You could reset($line) if you're using fetch like that, but I recommend otherwise.
2) You cannot use the same HTML name attribute twice, unless you add [] to the end of it. Then you can access it as an Array in PHP.
// otherpage.php
<?php
include 'connect.php'; $db = db(); $opts = $hdns = '';
if($q = $db->query('SELECT * FROM Eintraege')){
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$t = $r->Titel;
$opts .= "<option value='$t'>$t</option>";
$hdns .= "<input name='titel[]' type='hidden' value='$t' />";
}
// now you can echo $opts and $hdns where you want
}
else{
$errors[] = 'No result rows were found';
}
$q->free();
}
else{
$errors[] = 'database connection failure';
}
$db->close(); if(isset($errors))die(implode(' & ', $errors));
?>
To get the titel named inputs on the page you are submitting to, it's like:
<?php
if(isset($_POST['titel'])){
// get each one
foreach($_POST['titel'] as $t){
// $t is each one
}
}
?>
Note that getting data to put into hidden inputs then sending it back to the server is generally pointless, since you have access to that information anyways. You'll want to learn AJAX if you want something to go to the database based on Client input.
<!DOCTYPE html>
<html>
<head>
<title>Talenquiz2</title>
</head>
<body>
<?php
if (isset($_GET["controleer"]))
{
$vraag = $_GET["vraag"];
$juistantwoord = $_GET["juistantwoord"];
$foutantwoord1 = $_GET["foutantwoord1"];
$foutantwoord2 = $_GET["foutantwoord2"];
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen");
while($row = mysql_fetch_array($result))
{
if ($row['vraag'] == $vraag)
{
if ($row['juistantwoord'] == $juistantwoord)
{
echo "Juist!<br />";
}
else
{
echo "Fout!<br />";
}
}
}
mysql_close($con);
echo "\n<hr />\n";
}
$aantalvragen=1;
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen WHERE id='". $aantalvragen . "';");
$row = mysql_fetch_array($result);
The program is a quiz, it asks 5 questions with 3 chckbox 1 is corect and 2 are incorrect.
for ($aantalvragen=1; $aantalvragen<=5; $aantalvragen++)
{
$row = mysql_fetch_array($result);
}
her i lin
$vraag = $row['vraag'];
$juistantwoord = $row['juistantwoord'];
$foutantwoord1 = $row['foutantwoord1'];
$foutantwoord2 = $row['foutantwoord2'];
mysql_close($con);
?>
<form>
It doensn't show the values of the rows in my browser it shows only an open text and an open checkbox.
<input type="text" name="vraag" value="<?php echo $vraag; ?>" /><br />
<input type="checkbox" name="juistantwoord" value="<?php echo $juistantwoord; ?>" /><br />
<input type="checkbox" name="foutantwoord1" value="<?php echo $foutantwoord1; ?>" /><br />
<input type="checkbox" name="foutantwoord2" value="<?php echo $foutantwoord2; ?>" /><br />
<input type="submit" value="Controleer je antwoord" name="controleer" />
</form>
</body>
</html>
Your code is incorrect for fetching from the db
for(...) {
$row = mysql_fetch_array(...);
}
You simply loop over 5 lines of results, regardless of how many there may be, and assign the row array to $row... but do so for EVERY row without ever using them. So you end up trashing the first n-1 rows and come out of the loop with only row n saved.
If you're wrong with how many rows of data you're expecting, your 5-item loop may have only a 4-item result set to deal with, and the final row $row1 value will be the boolean FALSE that msyql_fetch returns when there's no more data.
Try something like this instead:
while($row = mysql_fetch_assoc($result)) {
echo ..... your stuff here ...
}
Far more reliable, doesn't depend on there being a known number of rows available, and will not output anything if there's no data at all.
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.