I got my database to work, and I can add my data and get return on it again. That is perfect, because it is the first time that I get it to work, and it opend up a lot of possibilies. So my next project here, is to ALTER my table in MySQL with a button. Until now it looks like this:
I can add a date, day, fromtime and totime. But I would like to have the possibility to change fx the day, if I make a mistake when I add the values to my database. I started on making an edit button in the right hand side. So overtime I make a new row, there will come a new edit button. But does anybody know how I can asign my button to the ALTER TABLE query? Or maybe a hint how to do it?
Best Regards to all
From Mads
EDITED CODE:
I have made the primary key in the database p_id. I also get a return from the p_id
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/arrangeTables.css">
</head>
<body>
<form method="post">
<h3>Add your worktime to database</h3><br>
<input type="date" name="date"><br><br>
<select name="day">
<option value="Mandag">Mandag</option>
<option value="Tirsdag">Tirsdag</option>
<option value="Onsdag">Onsdag</option>
<option value="Torsdag">Torsdag</option>
<option value="Fredag">Fredag</option>
<option value="Lørdag">Lørdag</option>
<option value="Søndag">Søndag</option>
</select>
<input type="time" name="fromtime">
<input type="time" name="totime">
<input type="submit" value="submit"><br><br>
</form>
</body>
<?php
$username = "root";
$password = "root";
$hostname = "127.0.0.1:3306";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br><br>";
//select a database to work with
$selected = mysql_select_db("danskebank",$dbhandle)
or die("Could not select any database");
// Insert to database
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', 'totime')";
$result = mysql_query($sql);
//Return records from database
$result = mysql_query("SELECT date, day, fromtime, totime FROM addWorkTime");
?>
<!-- Return from the database -->
<h3>Return from database:</h3><br>
<!-- headers -->
<tr>
<th class="column1">Date</th>
<th class="column2">Day</th>
<th class="column3">From</th>
<th class="column4">To</th>
</tr>
<!-- Now a row for each new set of data, here you probably need to
loop through some data set you retrieve from the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<table>
<tr>
<td class="resultcolumn4"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?></td>
<?php
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
?>
</tr>
<?php endwhile; ?>
</table>
</html>
To edit the specific row, you would need a Primary key in your mysql table. For example you call it: id. Now you would need to get the id from the table as well: SELECT id, date, day, fromtime, totime FROM addWorkTime
Use the $row['id']; in the while loop and replace the : <input type="button" value="Edit"> to: <a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?> now your url will look like: link_to_the_add_or_edit?id=1 and you can use: $_GET['id'] on the link_to_the_add_or_edit page. Now when you're on that page, you make sure you remember that id(SESSIONS) so you can use it on the submit action when you fill in the values.
Example of session:
session_start();
$_SESSION['id']=$_GET['id'];
on the link_to_the_add_or_edit page. After this you can update the row you want like this(when you submit something):
update danskebank SET date=['?'] where id= $_SESSION['id']
EDIT(regarding DarkBee's comment):
Instead of using sessions here, you can also store the $_GET['id'] in a hidden field like this:
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
and in the query use: $_GET['name_of_hidden_input'];
If you want to edit the values of the row try via url:
echo '<a href="edit.php?row_id=' . $row_id . '>Edit</a>'; //You should have id for every row
Create edit.php file and get row's id with $_GET['row_id']. Create form Add some input in it (like this one:<input type="datetime" />), and then handle it with another php file. You should execute your UPDATE query there. Like this :
$sql = "UPDATE row SET
date = '$date' ,
day = '$day' ,
fromtime = '$fromtime' ,
totime = '$totime'
WHERE id = $row_id;
";
mysql_query($sql);
But for all these you should have id for every row in the database.
Related
I have just started to learn PDO and have managed to do simple CRUD operations on one single table.
I am just doing a SELECT * from the table. But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID.
So my table structure is the following. I have a joke table with id and joketext and a foreign key authorId. The author table has authorId and name for the author.
Instead of doing SELECT * on the joke table, I would rather create a view with the following code:
SELECT
joke.joketext,
author.name
FROM
author
INNER JOIN joke
ON author.id = joke.authorid
But for the CRUD operations I would like to show the author.name in a dropdown instead, so the users don't erroneously put in wrong values.
This is how index.php looks like:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
$result = $dbConn->query("SELECT * FROM joke ORDER BY id DESC");
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Joke</td>
<td>AuthorId</td>
<td>Update</td>
</tr>
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>".$row['joketext']."</td>";
echo "<td>".$row['authorid']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
and my edit file looks like this:
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name=$_POST['joketext'];
$authorid=$_POST['authorid'];
// checking empty fields
if(empty($joketext) || empty($authorid)) {
if(empty($joketext)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($authorid)) {
echo "<font color='red'>Author field is empty.</font><br/>";
}
} else {
//updating the table
$sql = "UPDATE joke SET joke=:joketext, authorid=:authorid WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->bindparam(':id', $id);
$query->bindparam(':joketext', $joketext);
$query->bindparam(':authorid', $authorid);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$sql = "SELECT * FROM joke WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->execute(array(':id' => $id));
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$joketext = $row['joketext'];
$authorid = $row['authorid'];
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Joke</td>
<td><input type="text" name="joketext" value="<?php echo $joketext;?>"></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="authorid" value="<?php echo $authorid;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
Can someone show me a hint on at least the edit operations how the php code would like?
thanks
If you wish to provide a select element of available authors for the user to choose from on the edit page, rather than have them enter an ID number for an author, then you can select all the authors from the database and loop through them, building the options of your select element. A select element can show the user the name of the author, but pass the ID of the author back to the server. You can also pre-select an author to show the user the currently associated author by default and they only have to change it if it's wrong.
So first, select all the authors from the database:
$authorSql = 'SELECT * FROM author';
$authorQuery = $dbConn->prepare($authorSql);
$authorQuery->execute();
Then use that data to build a select element:
<select name="authorid">
<?php
while($author = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
if ($author['id'] == $authorid) {
//The author is currently associated to the joke, select it by default
echo "<option value=\"{$author['id']}\" selected>{$author['name']}</option>";
} else {
//The author is not currently associated to the joke
echo "<option value=\"{$author['id']}\">{$author['name']}</option>";
}
}
?>
</select>
The output might look something like this:
<select name="authorid">
<option value="1">George Carlin</option>
<option value="2" selected>Richard Pryor</option>
<option value="3">Don Rickles</option>
</select>
Whatever option the user selects, they'll see on the page what is between the <option></option> tags, but the form will pass the value of the value property to the server as the authorid parameter.
The code that generates the select element replaces the <input type="text" name="authorid" value="<?php echo $authorid;?>"> and remains within the <td></td> tags.
Hope I managed to address your actual need, let me know if I missed the intent of your question.
Note: my code isn't tested, so some adjustment may be required.
EDIT #1: Fixed incorrect variable names.
Here's my case (relatively new on php): I got a page "zoek_form.php" where you can enter 2 search values in a form (naam and categorie). When submitted, page "zoek.php" is loaded and a search will be performed (mysql 5.6). To perform the search the 2 values are obtained from the 2 session variables. So far so good, the search works and the rows are retrieved.
But now I want the user to be able to make a sequence (via ORDER BY) in zoek.php, based on a dropdown list. The selected value will be stored in a 3rd session variable. But now the problem: when selecting a sequence and submit the form, the first 2 session values are lost. I'm puzzled why. The essence of session variables is just storing the values and to be able to use them over and over again? (till they are overwritten or killed).
Of course I use session_start(); at the beginning of the php-script (otherwise it would not have worked at all ;-). Any ideas?
Here's zoek_form.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<?php session_start(); ?>
<form name="form1" method="POST" action="zoek.php">
<table border="0">
<tr><td>Naam product:</td>
<td><input type="text" size="50" name="form_naam"></td></tr>
<tr><td>Categorie:</td>
<td><input type="text" size="50" name="form_cat"></td></tr>
<tr><td></td>
<td align = "right"><input type="submit" name="B1" value="Zoeken">
</td></tr>
</table>
</form>
</body>
</html>
Here's zoek.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr><td>Sorteer op:</td>
<td><select name="form_sort">
<option value="Naam">Naam</option>
<option value="Categorie">Categorie</option>
</select></td>
<td><input type="submit" name="B1" value="Sorteer"></td></tr>
</table>
</form>
<?php
session_start();
require_once 'test_connect.php';
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
$_SESSION['form_sort'] = $_POST['form_sort'];
// The 3 lines below were used to check whether session vars were set
// echo $_SESSION['form_naam'];
// echo $_SESSION['form_cat'];
// echo $_SESSION['form_sort'];
function sorteren() {
global $sorteer;
$sorteer = $_SESSION['form_sort'];
if ($sorteer == "Naam") {
$sorteer = "ORDER BY naam";
}
else {
$sorteer = "ORDER BY categorie";
}
}
// Put values from zoek_form.php in vars.
$naam = $_SESSION['form_naam'];
$cat = $_SESSION['form_cat'];
// Check if user has set a sequence. If yes: call function sorteren(),
// if no: leave var $sorteer empty.
if (isset($_SESSION['form_sort'])) {
sorteren();
}
else {
$sorteer = "";
}
// Get rows from table product
$sql = "SELECT * FROM product WHERE naam LIKE '$naam%' OR categorie
LIKE '$cat%' $sorteer";
$result = $conn -> query($sql);
if ($result->num_rows > 0) {
// here code to retrieve rows etc.
}
// Give result free
$result -> free();
// Close connection
$conn -> close();
?>
</body>
</html>
Your form in zoek.php doesn't contain form_naam and form_cat so when you run
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
It sets those values to null. If you want to retain those values you could try passing them back again in the form with hidden input fields
<input type="hidden" name="form_naam" value="<?= $_SESSION['form_naam'] ?>">
<input type="hidden" name="form_cat" value="<?= $_SESSION['form_cat'] ?>">
Another way to prevent overwriting the session values is to only change them if the $_POST values are set
if(isset($_POST['form_naam']) && isset($_POST['form_cat'])) {
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
}
I have a list of 'orders' being pulled out, which consist of product name, description etc, one of the fields is quantity which is in an editable text box, next to that is an update button (which has an unique ID for that row pulled from the DB). Now when the update button is pressed, I want the quantity for that product to be updated. However i'm having problems getting the correct updated quantity to be matched with the ID of that row.
I can see that the problem is me setting the $quantity1 variable with just the last result pulled out inside the IF statement, but I can't think how to get it to relate the row i'm clicking on. Here is part of the code:
echo "<td>".$row['uName']."</td>";
echo "<td>".$row['prodID']."</td>";?>
<form method="post" action="reserved.php">
<td><input name="quantity1" type="text" id="quantity1" size="1" value='<?= $qty ?>' />
<td><input name="order2" id="order2" type="submit" class="button_add" value='<?= $row['ID']?>' /></td><?
echo "</tr>";
}
}elseif(!empty($studyDir) && $rowCount == 0){
?>
<?
}
}
if (isset($_POST['order2'])){
$order2 = $_POST['order2'];
$quantity1 = $_POST['quantity1'];
\\echo $quantity1;
$link3 = mysql_connect('localhost', '******', '******');
$SQL1 = "UPDATE ybsinter_stock.reservedStock SET qty = $quantity1 WHERE ID = '$order2'";
$result1 = mysql_query($SQL1);
mysql_close($link3);
unset($quantity1);
unset($order2);
header("Location:reserved.php");
}
?>
I can't see your form ending i.e. there is no <\form>.
Also note that declaring forms in tables (except entirely enclosed in a td) is bad HTML, run your code through the W3C validator.
Also try PHP heredocs for outputting blocks of HTML with embedded data....
echo <<<EOF
<tr>
<td>{$row['uName']}</td>
<td>{$row['prodID']}</td>
<td>
<form method="post" action="reserved.php">
<input name="quantity1" type="text" id="quantity1" size="1" value="{$qty}" />
// style this button right with CSS if you want ...
<input name="order2" id="order2" type="submit" class="button_add" value="{$row['ID']}" />
</form>
</td>
</tr>
EOF;
The above form will only submit data to your script with the id that you're interested in..
Your SQL query seems roughly correct, but beware of SQL injection - please bind your variables into your queries instead of inserting them. Use the mysqli or PDO libraries instead of the outdated basic mysql functions.
$mysqli = new mysqli( /* your connection params here */ );
$sql1 = 'UPDATE ybsinter_stock.reservedStock SET qty = ? WHERE ID = ?';
$stmt = $mysqli->query( $sql1);
$stmt->bind_param( 'sd', $quantity1, $order2);
$result = $stmt->execute();
See php code below:
I have built the html form and the dropdown menu in the html form using <<<_END _END tags in php. also I added the following php code at the top of the htmlform that I had believed would allow me to enter a student name, student ID and select a course from the dropdown menu in the form. once those 3 values were entered in the form, the info should be added to the table enrolment in my mysql database. but i have had no luck figuring this out...
//connect3.php--login information to my mysql database//
<?php
define ('HOST', 'localhost');
define ('USER', 'root');
define ('PASS', '******');
?>
// html form and connection code//
<?php
include 'connect3.php';
$link = mysql_connect (HOST, USER, PASS) or die(mysql_error());
mysql_select_db ('milleruniversity', $link);
// Added mysql_real_escape() to protect against SQL-Injection
$code = mysql_real_escape( $_POST['code'] );
$uid = mysql_real_escape( $_POST['uid'] );
$studentname = mysql_real_escape( $_POST['studentname'] );
// Insert a row of information into the table "enrolment"
$query = "INSERT INTO enrolment (code, uid, studentname) VALUES('$code', '$uid', '$studentname')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
echo <<<_END
<table border='1'cellpadding="10">
<tr>
<td>
<h4>Miller University Registration Form</h4>
<p>Please Register as a new Student or current student for the following courses below.</p>
</td>
</tr>
<form action="draft5.php" method="post"><pre>
<tr>
<td>
Student Name <input type="text" name="studentname" maxlength="30"/>
</td>
</tr>
<tr>
<td>
Student ID <input type="text" name="uid" maxlength="11"/>
</tr>
</td>
<tr>
<td>
Select a course <select name="code" size="1">
<option value="DC-00040">Digital Communications</option>
<option value="VC-00030">Visual Culture</option>
<option value="WP-00080">World Politics</option>
</select>
</tr>
</td>
<tr>
<td>
<input type="submit" value="Submit to Register" />
</tr>
</td>
</pre></form>
</table>
_END;
mysql_close($link);
?>
It seems to me that you use this draft5.php page to display the form and to insert a row in your database. In that case the problem may come from the missing isset() around the $_POST data. (the first time you load the page the POST values are not set).
You could use this code :
if( (isset($_POST['code']) AND (isset($_POST['uid']) AND (isset($_POST['studentname']){
//process the data base treatment and display an acknoledgment of the insert
// Check if these new code, uid and studentname respect the primary key constraint
}
else{
// Display your form
}
You could also consider using backticks ` around the names of your tables and colomns.
If you want to prevent the same student to register twice in the same course you need to add primary keys in your tables. But this is not enough, indeed if you perform the insert request with a contraint violation on the primary key MySql will return an error. What you can do is check if the key exists prior to the insert request, if yes notify the user, if no perform the insert request.
I have a small (42 hours) problem with my code trying to edit article
- just the basic editNews.php
When I choose article to edit the data appears in the forms from the DB and when
I hit "update" it returns no error but the data wasn´t updated
<?PHP
connection to database blah blah
?>
<?php
if(isset($_POST['update']))
{
$newsid = $_POST['newsid'];
$date=$_POST['date'];
$time=$_POST['time'];
$location=$_POST['location'];
$result=mysql_query("UPDATE news SET date='$date',time='$time',location='$location', WHERE newsid=$newsid");
header("Location: listNews.php");
}
}
?>
<?php
$newsid = $_GET['newsid'];
$result=mysql_query("select * from news where newsid=$newsid");
while($res=mysql_fetch_array($result))
{
$date = $res['date'];
$time = $res['time'];
$location = $res['location'];
}
?>
This is the form - just the normal one....
<form method="post" action="editNews.php" name="form1">
each item is like
<input type="text" name="headline" value="<?php echo $location;?>" id="UserName">
and
<input type="hidden" name="newsid" value=<?php echo $_GET['newsid'];?>
<input name="update" type="submit" value="update" />
Most likely there is something that I don´t see but "seeing" has taken almost 2 days now
... Is there a possibility I don´t have "edit" privileges in the mySql?
How do you know there was no error? Your code lacks:
print mysql_error();
Add it right after the UPDATE query.
Also your code is most likely to fail whenever the submitted content itself contains single quotes. To send correct SQL to the database it's advisable to apply mysql_real_escape_string() on all input variables.
Try
$result= mysql_query('UPDATE news SET
date = "'. $date .'",
time = "'. $time. '",
location = "' .$location. '"
WHERE newsid = '.$newsid.';') OR die(mysql_error());