I have gone over my code many many MANY times and added any missing brackets or semi-colons but still whenever I upload this code to my website and load the page I still get a completely blank screen. The code was from an O'Reilly book so I went and checked the website if there are any reported errors in the book but found nothing related to this particular example.
I don't feel like it's an issue with permissions because I think the page would at least report one of the errors I coded into it. Could it have to do with the versions of PHP or MySQL I am using? I was able to connect to the database in the past and query it but writing just isn't happening. I am at a complete loss at this point. All I want to do is write to my MySQL database and party :(
Here is the code:
<?php
require_once 'login.php';
// Create connection
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
// Check connection
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['avail']))
{
$avail = get_post('avail');
$query = DELETE FROM test WHERE avail='$avail';
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['id']) &&
isset($_POST['item_name']) &&
isset($_POST['avail']))
{
$id = get_post('id');
$item_name = get_post('item_name');
$avail = get_post('avail');
$query = "INSERT INTO test VALUES" .
"('$id','$item_name','$avail')";
if (!mysql_query($query, $db_server))
{echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
}
?>
<form action="index.php" method="post"><pre>
Line Number <input type="text" name="id" />
Product Name <input type="text" name="item_name" />
Quantity Available <input type="text" name="avail" />
<input type="submit" value="ADD RECORD" />
</pre></form>
<?php
$query = "SELECT * FROM test";
$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);
?>
<pre>
Line Number $row[0]
Product Name $row[1]
Quantity Available $row[2]
</pre>
<form action="index.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="avail" value="$row[2]" />
<input type="submit" name="DELETE RECORD" /></form>
<?php
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
you have error in the delete statment , try out this code :
<?php
require_once 'login.php';
// Create connection
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
// Check connection
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['avail']))
{
$avail = get_post('avail');
$query = "DELETE FROM test WHERE avail='$avail'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['id']) &&
isset($_POST['item_name']) &&
isset($_POST['avail']))
{
$id = get_post('id');
$item_name = get_post('item_name');
$avail = get_post('avail');
$query = "INSERT INTO test VALUES" .
"('$id','$item_name','$avail')";
if (!mysql_query($query, $db_server))
{echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
}
?>
<form action="index.php" method="post"><pre>
Line Number <input type="text" name="id" />
Product Name <input type="text" name="item_name" />
Quantity Available <input type="text" name="avail" />
<input type="submit" value="ADD RECORD" />
</pre></form>
<?php
$query = "SELECT * FROM test";
$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);
?>
<pre>
Line Number $row[0]
Product Name $row[1]
Quantity Available $row[2]
</pre>
<form action="index.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="avail" value="$row[2]" />
<input type="submit" name="DELETE RECORD" /></form>
<?php
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
If no errors are being displayed add the following to the top of your file, it will allow for errors to be shown:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Please ensure that you are displaying errors.
ini_set("display_errors", "1");
You can also create a new page with just
phpinfo();
to check that PHP is running (and what PHP configuration you have).
Related
There are two php files one contains the form and the other contains the code to insert the form data to the table in a database.
This is the submit form code from the first file
<form name="form" action="insert_dataE.php" onSubmit="return
validation()" method="post" id="formServiceEntry">
<fieldset id="fieldSetServiceEntry">
<legend align="center">Please fill the form</legend>
<p class="FieldHeading"><i>Vehicle No(*): </i></p>
<input id="VehicleNoFieldArea" type="text" name="VehicleNoField"
size="6" maxlength="8"/>
<p class="FieldHeading"><i>Description(*):</i></p>
<textarea id="descriptionFieldArea" name="descriptionField"
rows="2" cols="20" size="15" maxlength="18"></textarea>
<p class="FieldHeading"><i>Total(*):</i></p>
<input id="totalFieldArea" name="totalField" type="text"
size="4" maxlength="4"/>
<p id="amountFieldHeading"><i>Bill(*):</i></p>
<input id="amountFieldArea" name="amountField" type="text"
size="3" maxlength="3" onKeyUp="balance();" />
<br/>
<div id="divisionRadioButton">
<h3 id="radioButtonHeading">Service(*):</h3>
Service
<input class="textFields" type="radio"
name="serviceSelection" value="service" checked />
<br/>
Wash
<input class="textFields" type="radio"
name="serviceSelection" value="wash" />
</div>
<p id="balanceFieldHeading"><i>Balance(*):</i></p>
<input id="balanceFieldArea" name="balanceField" type="text"
size="4" maxlength="4"/>
</fieldset>
<input class="btnsSE" type="submit" name="Button" value="Submit" />
<input class="btnsSE" type="reset" name="Button" value="Reset Form"/>
<input type="button" class="btnsSE" value="Back to the staff
interface" onClick="window.location='staffE.php';"/>
</form>
This is the insert data code from the second file
<?php
// Connects to your Database
$conn=mysql_connect("localhost", "webgeek1_service", "6defyu4642070") or
die(mysql_error());
mysql_select_db("webgeek1_software_order", $conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
$dateAndTime = date('y-m-d H:i:s',time());
$vehicleNo=mysql_real_escape_string($_POST['VehicleNoField']);
$description=mysql_real_escape_string($_POST['descriptionField']);
$amount=mysql_real_escape_string($_POST['amountField']);
$service=mysql_real_escape_string($_POST['serviceSelection']);
// Build an sql statment to add the query details
$sql="INSERT INTO `webgeek1_software_order`.`application`(`serialNo`,
`dateAndTime` , `vehicleNo` , `description` ,`amount`,`service`)
VALUES
('$id',
'$dateAndTime','$vehicleNo','$description','$amount','$service')";
$result = mysql_query($sql, $conn);
if($result)
{
echo "<p id='headingInsertData'>Service Station Web Application</p>";
echo "<p id='receiptHeading'>Receipt</p>";
echo "<div id='mainFieldsInsertData'>";
echo "Serial No: " . " " . $id;
echo "<br/>";
echo "Date and Time: " . " " . $dateAndTime;
echo "<br/>";
echo "Vehicle No: " . " " . $vehicleNo;
echo "<br/>";
echo "Description: " . " " . $description;
echo "<br/>";
echo "Amount: " . " " . $amount;
echo "<br/>";
echo "Service:" . " " . $service;
echo "<br/>";
echo "<br/>";
echo"Thanks for using our services";
echo "</div>";
echo "<div id='footerInsertData'>";
echo "<i>Developed by: Web Geeks - Information Technology (IT)
Company</i>";
echo "</div>";
echo "<div align='center'>";
echo "<input class='btns' type='button' value='Print'
onClick='javascript: window.print();'/>";
echo "<input type='button' class='btns' value='Back to the
Application' onClick='newDoc()'/>";
echo "</div>";
}
else
{
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The error you're having (Duplicate entry '51' for key 'PRIMARY') seems pretty logical since you're giving your specified ID to row instead of writing automatically. Moreover, you're using ID based off of the amount of rows there currently are. This leads to MySQL error with ID duplication.
To solve this issue:
Modify serialNo column and tick a checkbox on A_I column (AUTO_INCREMENT). This will make sure you will always have unique ID.
Remove entirely this part in your code:
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Modify your query:
This is modified already
$sql="INSERT INTO `webgeek1_software_order`.`application` (`dateAndTime`, `vehicleNo`, `description`,`amount`, `service`) VALUES('$dateAndTime', '$vehicleNo', '$description', '$amount', '$service')";
I believe database should automatically set what next ID should come after inserting new data. This will prevent your from getting such errors as ID duplication because you're no longer inserting your own number.
A side note (but important): you should use mysqli or PDO statements because mysql extension is deprecated (and is even removed in PHP 7.0.0).
In the structure for my table in phpmyadmin, I needed to set the column 'serialNo' to AI (Autoincrement) and in the insert data code, I needed to comment the lines:
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Similarly, I needed to remove the 'serialNo' from the insert query in the same file. At last I needed to comment the lines :
echo "Serial No: " . " " . $id;
echo "<br/>";
in the insert data code
This is my code :
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="SubCategories"; // Table name
$con=mysqli_connect("$host", "$username", "$password", "$db_name");
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
//print_r($_POST); //print all checked elements
//echo "<br>".$email, $_POST["update"][$i];
//mysql_real_escape_string ($route )
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$res2=mysqli_query("UPDATE ".$tbl_name." SET subCat2 = '" . $y . "' WHERE id =". $h,$con);
if ($res2){
}
else{
echo "<h1>NOT WORKING!</h1>";
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM $tbl_name");
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['subCat2'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['subCatNum'] . '"/>';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>
I can't update the table in my database. I am able to extract the variables properly and echo them, however it does not work.
I have gotten the following error in the past 'no database selected'.
I think that you forgot to select the database. Try to put this after your connection:
if (!mysqli_select_db($con, $db_name)) {
die("Uh oh, couldn't select database $db_name");
}
If this happens, double check the name, permissions, etc.
Try it again, but without the quotes surrounding the DB connection variables. I mean, they are variables & not strings, right?
Original with quotes:
$con=mysqli_connect("$host","$username","$password","$db_name");
Cleaned without quotes:
$con=mysqli_connect($host,$username,$password,$db_name);
You should change your code adding the snippet below. This way you can debug your code better:
if (!$result = $mysqli->query("YOUR-SQL", MYSQLI_USE_RESULT)) {
printf("Error: %s\n", $mysqli->error);
}
...do something here..
$result->close();
Someone in my class helped me figure it out, thanks though! Here is the code, just wonderful :)
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$con=mysqli_connect($host,$username,$password,$db_name);
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$sql2="UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h;
//$res2=mysqli_query("UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h,$con);
$res2=mysqli_query($con,$sql2);
if ($res2){
}
else{
echo "<h1>NOPE!</h1>";
print "Failed to connect to MySQL: " . mysqli_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM ".$tbl_name);
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['name'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['id'] . '"/>';
//echo '<input type="text" class="a" name="holder2[]" id="checkbox-1" class="custom" value="' . $row['price'] . '" />';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>
I want to retrieve the input value entered by the user and send it to the database. But for some reason it inserts a blank space in the table, instead of the value! Does someone know what's wrong?
<form method="post" name="name" action="pt2.php" >
<?php
//$mysql->commit();
echo "<h3>";
echo "Please enter the name for each seat:<br><p> </p>";
echo "";
foreach($_POST['seats'] AS $seat) {
$rowId = substr($seat, 0, 1);
$columnId = substr($seat, 1);
echo $rowId . $columnId . '<input type="hidden" name="seats[]" value="' . $seat . '"><input name="' . $seat . 'name" type="text"/></br>';
}
?>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
pt2.php
<?php
// Connect to MySQL
mysql_connect("localhost", "root", "root") or die("Connection Failed");
mysql_select_db("tickets")or die("Connection Failed");
$namei = $_POST[$seat . 'name'];
foreach ($_POST['seats'] as $seat){
echo $seat;
echo $namei;
$query = "INSERT INTO seatnames (seatname) VALUES ('$namei')";
mysql_query($query) or die(mysql_error());
}
?>
I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.
I am pretty new to PHP and I am trying to make an inventory database. I have been trying to make it so that a user can enter a card ID and then amount the want to add to the inventory and have it update the inventory. For example someone could type in test and 2342 and it would update test. Here is what I have been trying with no success:
add.html
<body>
<form action="add.php" method="post">
Card ID: <input type="text" name="CardID" />
Amount to Add: <input type="text" name="Add" />
<input type="submit" />
</form>
</body>
</html>
add.php
<?php
$link = mysql_connect('host', 'username', 'password');
if (!$link){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tdm_inventory", $link);
$add = $_POST[Add]
mysql_query("UPDATE cardLists SET AmountLeft = '$add' WHERE cardID = 'Test'");
echo "test successful";
mysql_close($link);
?>
I think you are missing quotes around your POST value for one. You are also committing one of the cardinal sins of PHP development putting the variables right in your SQL string like that. Try this instead:
<?php
$link = mysql_connect('host', 'username', 'password');
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tdm_inventory", $link);
if (mysql_errno())
{
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
$add = $_POST["Add"]
$query = sprintf("UPDATE cardLists SET AmountLeft = AmountLeft + %s WHERE cardID = 'Test'", mysql_real_escape_string($add));
mysql_query($query);
if (mysql_errno())
{
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
echo "test successful";
mysql_close($link);
?>