How to post data to mySQL database through PHP form? - php

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."')";

Related

Function get_post and return mysqli_real_escape_string - PHP

I'm a beginner at coding (I just have a small experience with Visual Basic and Pascal) and now I'm trying to learn some Web Development using O'Reilly's book "Learning PHP, MySQL, JavaScript, CSS & HTML 5".
The problem is that he is using MySQL instead of MySQLi, so I need to do small changes when I'm following thought the exercises.
In a chapter called "Accessing MySQL databases using PHP" he built a form where the user can add a new book (with title name, author, year, category and ISBN) to the database. My problem is that I have some error than doesn't allow to see in the web page the new book submitted.
I'm not sure, but I think it has to be something with the get_post and mysqli_real escape_string part.
This is the code I've written:
<?php //sqltest.php
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysqli_error($db_server));
mysqli_select_db($db_server, $db_database)
or die ("Unable to select database: " . mysqli_error($db_server));
//Deleting a record.
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn = '$isbn'";
if (!mysqli_query($db_server,$query))
echo "DELETE failed: $query<br>" .
mysqli_error($query) . "<br><br>";
}
//Add new elements to the database.
if (isset($_POST['author']) && //Isset -> Determine if a variable is set and is not NULL.
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($db_server, 'author');
$title = get_post($db_server, 'title');
$category = get_post($db_server, 'category');
$year = get_post($db_server, 'year');
$isbn = get_post($db_server, 'isbn');
}
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
//Displaying the form.
echo <<<_END
<form action = "sqltest.php" method="post"> <pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
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 = mysqli_query($db_server, $query);
if (!$result) die ("Database acess failed: " . mysqli_query_error($result));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<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>
_END;
}
function get_post($db_server, $var)
{
return mysqli_real_escape_string($db_server, $_POST[$var]);
}
mysqli_close($db_server);
?>
Just to explain my problem better: I fill the form with the details from the new book and then I submitted it but the new book doesn't appear on the web page (like the ones added before using MySQL command line).
Thanks for your time,
David
There is an error in your code, specific the name of database columns.
$query = "INSERT INTO classics (author, title, category, year, isbn) VALUES ('$author', '$title', '$category', '$year', '$isbn');";

PHP trying to connect to mysql database! but the code doesnt work

PHP trying to connect to MySQL database! but the code doesn't work.
Here is the code, when I put the code in a PHP file, the display shows actually the code I wrote.
I am stuck, please help!
<?php // sqltest.php
require_once '../../htdocs/login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post($conn, 'isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>" .
$conn->error . "<br><br>";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($conn, 'author');
$title = get_post($conn, 'title');
$category = get_post($conn, 'category');
$year = get_post($conn, 'year');
$isbn = get_post($conn, 'isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author">
Title <input type="text" name="title">
Category <input type="text" name="category">
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 = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<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>
_END;
}
$result->close();
$conn->close();
function get_post($conn, $var)
{
return $conn->real_escape_string($_POST[$var]);
}
?>
I am reading this book called Learning PHP, MySQL, & JavaScript
4th Edition By Robin Nixon, but when I write the exact code, it doesn't show like in the book but I get that like in the photo. I am trying to connect MySQL with PHP, using xampp. I created also the php.login file. I wrote my username and password, and saved it in the same directory with this code!
please help

Php drop down to post choice to another table

I have a script in php that pulls information for a dropdown list. When I hit post, I want what ever my selection is from the drop down list to post in another Table called techissuses.
<form action="insert.php" method="post">
<?php mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("mysqli")or die("Connection Failed");
$query = "SELECT * FROM manufactures"; $result = MySQL_query($query); ?> <select name="select1">
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
< <option value="<?php echo $line['name'];?>">
<?php echo $line['name'];?>
</option> <?php } ?> </select>
First name: <input type="text" name="firstname">
Last name: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
This is the insert.php that will write to Techissues enter code here:
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$Techissues = mysqli_real_escape_string($con, $_POST['techissues']);
$sql="INSERT INTO Persons (FirstName, LastName, Age, Techissues)
VALUES ('$firstname', '$lastname', '$age', '$techissues')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

PHP Issue with deleting from MySQL

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')) {
...
}

web form does not add or delete from mysql table

I'm working on a basic web form (using PHP and smarty templates) that allows users to add and delete data from a mysql database table. The data and form display fine, but nothing happens when a user tries to add or delete records from the table(not even the "cannot delete/add record' error message displays). Here is what the code looks like:
<?php //smartytest.php
$path =$_SERVER['DOCUMENT_ROOT'];
require "$path/Smarty/Smarty.class.php";
$smarty = new Smarty();
$smarty->template_dir = "$path/temp/smarty/templates";
$smarty->compile_dir= "$path/temp/smarty/templates_c";
$smarty->cache_dir="$path/temp/smarty/cache";
$smarty->config_dir="$path/temp/smarty/configs";
require_once ("$path/phptest/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) or die("unable to select database: " . mysql_error());
if(isset($_POST['author'])&&
isset($_POST['title'])&&
isset($_POST['category'])&&
isset($_POST['year'])&&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category=get_post('category');
$year = get_post('year');
$isbn =get_post('isbn');
if (isset($_POST['delete']) && $isbn !='')
{
$query= "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query))
{
echo "DELETE failed: $query<br>". mysql_error() . "<p>";
}
}
else
{
$query = "INSERT INTO classics VALUES" . "('$author','$title', '$category', '$year', '$isbn')";
if (!mysql_query($query))
{
echo "INSERT failed: $query<br>" . mysql_error() . "<p>";
}
}
}
$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)
{
$results[] = mysql_fetch_array($result);
}
mysql_close($db_server);
$smarty->assign('results', $results);
$smarty->display("smartytest.tpl");
function get_post($var)
{
return mysql_escape_string($_POST[$var]);
}
?>
Also, here is the Smarty template file:
<html><head>
<title>Smarty Test</title>
</head><body>
<form action="/phptest/smartytest.php" method="post"><pre>
Author <input type="text" name="author">
Title<input type="text" name="title">
Category<input type="text" name="category">
Year<input type="text" name="year">
ISBN<input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
{section name=row loop=$results}
<form action="/phptest/smartytest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="{$results[row].isbn}">
<pre>
Author {$results[row].author}
Title {$results[row].title}
Category {$results[row].category}
Year {$results[row].year}
ISBN {$results[row].isbn}
<input type="submit" value="DELETE RECORD"></form>
</pre>
{/section}
</body></html>
My best guess is that there is something wrong with the nested if statements (which may be why not even the error message is displaying), but I've double checked the code and it looks good (at least to me). Does anyone notice anything wrong with this? I can post a screen of what the page looks like if that will help.
You are checking for the existence of author, title, category, year, isbn with isset(..) before checking to see what type of action was taken. There variables (like $_POST['author'] are not set. Reason is that you have multiple forms on the page. Only the inputs that are within the form that is submitted are available in $_POST.
In this case, you could simply do:
if (isset($_POST['delete'])
&& isset($_POST['isbn'])
&& strlen($_POST['isbn'])) {
// Remove record code here
}
else {
// Add record code here
}

Categories