i have Form what populate fields from database, can you show me php to insert data to database, each score to own row in database (id,name,score)
Updated: whit theis codes it prints like this:
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
now i use this form:
<form action="insert_action2.php" id="form2" title="form2" method="post">
<table>
<?php
$link = mysqli_connect("localhost", "form", "form", "form");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM form2" ;
$players = $link->query($sql);
while($player = $players->fetch_assoc()){
?>
<tr>
<td>
<input type="text" name="id" id="id" value="<?php echo $player["id"]; ?>">
<input type="text" name="name" id="name" value="<?php echo $player["name"]; ?>">
</td>
<td>
<input type="text" name="score" id="score" size="2" value="<?php echo $player["score"]; ?>">
</td>
</p>
<?php
}
$link->close();
?>
</tr>
</table>
<input type="submit" value="update scores">
</form>
insert to database -insert_action2.php
i have tried couple arrays and foreach but cant get those working right...
<?php
foreach($_POST as $players => $value) {
$id = mysqli_real_escape_string($link, $_POST['id']);
$name = mysqli_real_escape_string($link, $_POST['name']);
$score = mysqli_real_escape_string($link, $_POST['score']);
$sql = "UPDATE form2 SET score='$score', name='$name' WHERE id=$id";
if(mysqli_query($link, $sql)){
echo "lines updated to database: <br>$id - $name - $score <br><br><p><p>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
You'll need to use:
$sql = "insert into `form2`(`name`, `score`) VALUES ('{$name}', '{$score}')";
When you use some variable inside a string, you need to scape the variable.
Or use this way:
$sql = "insert into `form2`(`name`, `score`) VALUES ('" . $name . "', '" . $score . "')";
Related
Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck
I am new to PHP and I am following a tutorial that gets information from a mySQL database table by the row and outputs a form to create new table rows. For some reason I can't figure out what is wrong with my code? The page is blank when I refresh the page and I have been staring at this code forever. Does anybody know what I am doing wrong? The database connection is fine as it is used on another page and i have checked.
The mySQL database I have is extremely simple, with 1 table called users that has 5 columns (ID, username, firstName, lastName, title) with the ID being a unique field.
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['delete']) && isset($_POST['ID']))
{
$id = get_post('ID');
$query = "DELETE FROM users WHERE ID='$id'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>" .
mysql_error() . "<br><br>";
}
if (isset($_POST['ID']) &&
isset($_POST['username']) &&
isset($_POST['firstName']) &&
isset($_POST['lastName']) &&
isset($_POST['title']))
{
$id = get_post('ID');
$username = get_post('username');
$firstName = get_post('firstName');
$lastName = get_post('lastName');
$title = get_post('title');
$query = "INSERT INTO users VALUES" .
"('$id', '$username', '$firstName', '$lastName', '$title')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br>" .
mysql_error() . "<br><br>";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
ID <input type="text" name="ID">
username <input type="text" name="username">
firstName <input type="text" name="firstName">
lastName <input type="text" name="lastName">
title <input type="text" name="title">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM users";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
ID $row[0]
username $row[1]
firstName $row[2]
lastName $row[3]
title $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="title" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
Any help would be super awesome!
You are trying to retrieve variables with the wrong way.
Example
$username = get_post('username');
should be
$username = $_POST['username'];
You should do the same with the same code that you are trying to retrieve post variables.
And the query to insert values should be
$query = "INSERT INTO users VALUES('".$id."', '".$username."', '".$firstName."', '".$lastName."', '".$title."')";
i am trying to submit data from a html form using php to a sql database.
It completed up to part 5 but doesn't appear to be any actual data in any of the table rows apart from the auto increment userID. Also is this code protected from SQL Injection?
Also what is the best way to input a datestamp into the SQL database? for example a ClientSince field.
Here is my clientsubmit.php
<?php
// Create connection
echo "Made it! Part 1";
$con=mysqli_connect("xxx","xxx","xxx","xxx");
echo "Made it! Part 2";
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$txtNam = mysql_real_escape_string($_POST["name"]);
$txtEmail = mysql_real_escape_string($_POST["email"]);
$txtSlots = mysql_real_escape_string($_POST["slotcount"]);
$txtSecurity = mysql_real_escape_string($_POST["passcode"]);
echo "Made it! Part 3";
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
echo "Made it! Part 4";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Made it! Part 5";
mysqli_close($con);
?>
And here is my form:
<form name="form" class="form" action="clientsubmit.php" method="post">
<input type="text" name="sum2" readonly hidden="true" onChange="updatesum()" value="1.5"/><br>
Ingame Name: <input type="text" name="name" class="txtbox" /><br><br>
Email Address: <input type="text" name="email" class="txtbox" /><br><br>
Passcode: <input type="text" name="passcode" class="txtbox2" /><br><br>
Slot Count: <input type="text" name="slotcount" onChange="updatesum()" class="txtbox2" value="10"/><br><br>
Per Month: <input name="sum" readonly class="txtboxtotal" style="border: 0px;" value="15"> Million<br><br>
<input type="submit">
</form>
Added these:
echo "Made it here! 3 ";
echo " ";
echo $txtNam;
echo " ";
echo $txtEmail;
echo " ";
echo $txtSlots;
echo " ";
echo $txtSecurity;
echo " ";
and it appears that the variables are not holding any data before submitted to the database.
Got it working with the help of you guys, here is the finished code:
<?php
// Create connection
$con=mysqli_connect("xxxx","xxxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con, $_POST["email"]);
$txtSlots = mysqli_real_escape_string($con, $_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con, $_POST["passcode"]);
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
The issue is you are using mysql_real_escape_string() and using mysqli_*()
change mysql_real_escape_string() to mysqli_real_escape_string()
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con,$_POST["email"]);
$txtSlots = mysqli_real_escape_string($con,$_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con,$_POST["passcode"]);
You mentioned above submit.php and you post form at clientsubmit.php.
I'm new to php and I've been trying to get a form to post to values to a database.
I've successfully connected to the database, because I can pull values from the table and display them in the HTML.
I believe the mysqli_query is correct because I can replace the $variables with examples and they work and do post.
However, I can't seem to find the correct combination of how to insert the $name and $desc variables I've tried $name, '$name', and '$_POST[friendname]. What am I missing?
<?php
include 'includes/connect.php';
$name = $_POST[friendname];
$desc = $_POST[desc];
//WRITE TO DATABASE
if(!$_POST) {
echo "Form info: " . $name . " " . $desc;
echo "<br />Use the form below to add a new person! <br /><br />";
}
else {
$query = "INSERT INTO Friends (ID, Name, Description) VALUES ('NULL', $name, $desc)";
mysqli_query($sql, $query);
echo "<br />You've added " . $name . "<br /><br />";
}
$result = mysqli_query($sql,"SELECT * FROM Friends");
while($row = mysqli_fetch_array($result)) {
echo "<strong>" . $row['Name'] . "</strong> - " . $row['Description'];
echo "<br>";
}
?>
<p><strong>Add a new person to the database</strong></p>
<!-- FORM -->
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
try not to put the id into the query, I assume that this column is auto-increment.
Also you should put the variables as show below
$query = "INSERT INTO Friends (Name, Description)
VALUES ('".$name."', '".$desc."')";
NOTE: If you can show us what data is storing in your database it would be of help
try to replace
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', $name, $desc)";
to
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', {$name}, {$desc})";
instead of write SQL statement as string,you can use PDO
I've had to wrap the desc in backquotes which is MySQL-speak for "this is a variable name" because desc is a keyword. You will make your life easier if you change the column name to description instead.
PDO comes as standard on most PHP installations and does make things a lot easier.
<?php
$pdo = new PDO("mysql:host=localhost;dbname=mysql", "user", "password");
if (isset($_POST))
{
$name = $_POST['friendname'];
$desc = $_POST['desc'];
echo "Form info: " . $name . " " . $desc;
// WRITE TO DATABASE
$sql = "INSERT INTO Friends(friendname, `desc`) VALUES (:fn, :d)";
$query = $pdo->prepare($sql);
$query->execute(array(':fn'=>$name, ':d'=>$desc));
echo "<br />You've added " . $name . "<br /><br />";
die;
}
?>
<p>Use the form below to add a new person!</p>
<p><strong>Add a new person to the database</strong></p>
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
There is a reasonable example of executing a "SELECT *" here:
How to fetch row with PDO
I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}