Adding with PHP to a MySQL database - php

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);
?>

Related

PHP MySQL UPDATE query not posting value from text box

I have a form with a select list populated from a database. When the query is executed, a success message is returned however the database is not updated.
Here is the form:
<form id="formPrice">
<?php
$conn = new mysqli('localhost', 'something', 'something', 'something')
or die ('Cannot connect to db');
$result = $conn->query("SELECT PlotNumber FROM Developments WHERE Development = 'GREENGRAVES' AND Price = 'BOOKED'");
echo "<select name='plot_update'>";
while ($row = $result->fetch_assoc()) {
echo "<option value=\"Plot\">" . $row['PlotNumber'] . "
</option>";
}
echo "</select>";
?>
<input name="price" type="text" id="price">
<input name="update" type="submit" class="update_price">
</form>
Here is the ajax request:
$('.update_price').click(function() {
var FormData = $('form').serialize();
$.ajax({
type: "POST",
url: '../php/update_price.php',
data : FormData,
success:function(html){
document.getElementById("result_two").innerHTML=html;
}
});
return false;
});
Here is the php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$price = $_POST['price'];
$plot = $_POST['plot'];
$sql = "UPDATE Developments SET Price = '".$price."' WHERE PlotNumber = '".$plot."' ";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
The page displays "record updated successfully" in the result div, however database entry remains unchanged. Any ideas why? I'm stumped.
The error seemed to be with this line in the front end form:
echo "<option value=\"Plot\">" . $row['PlotNumber'] . "</option>";
When I changed to:
echo "<option>" . $row['PlotNumber'] . "</option>";
it worked!
There is issues with form field under php script:
change your php script to the following:
<form id="formPrice">
<?php
$conn = new mysqli('localhost', 'something', 'something', 'something')
or die ('Cannot connect to db');
$result = $conn->query("SELECT PlotNumber FROM Developments WHERE Development = 'GREENGRAVES' AND Price = 'BOOKED'");
echo "<select name='plot'>";
while ($row = $result->fetch_assoc()) {
echo "<option value=" . $row['PlotNumber'] . ">" . $row['PlotNumber'] . "</option>";
}
echo "</select>";
?>
<input name="price" type="text" id="price">
<input name="update" type="button" class="update_price">
Always make sure - Select option value needs to have the actual value of the record and select field will have the form field name.

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

How can I perform search operation in MySQL database with help of PHP?

I have a database table with fields Name, EmailAddress, Qualification I want to perform the search using name, emailaddress, qualification and need to display the user details in my web page can anybody tell how can I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$name=$_POST['name'];
//$email=$_POST['email'];
//$qualification=$_POST['qualify'];
$sql = "SELECT * FROM form WHERE Name ='kumar' OR EmailAddress = 'kumar#gmail.com' OR Qualification = 'BE' ";
$result=$conn->query($sql);
while($row = $result->fetch_assoc())
{
echo 'Name: '.$row['Name'];
echo '<br /> EmailAddress: ' .$row['EmailAddress'];
echo '<br /> Qualification: '.$row['Qualification'];
echo '<br /> DOB: '.$row['DOB'];
}
mysql_close($con);
$con = mysql_connect ("localhost", "root", "");
mysql_select_db ("myDB", $con);
if (!$con) { die ("Could not connect: " . mysql_error()); }
$sql = mysql_query("SELECT * FROM search WHERE name LIKE '%arun%' OR EmailAddress LIKE '%arun%' OR Qualification LIKE '%arun%' ");
$con->query($sql);
if(count($sql)>0 || $sql !=NULL){
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
echo 'Name: '.$row['name'];
echo '<br /> Email: ' .$row['email'];
echo '<br /> Address: '.$row['address'];
}
}
else{
echo 'your error here';
}
mysql_close($con);
Use PDO, donĀ“t use mysql or even mysqli. Its not even supported anymore in the latest PHP versions.
$host = 'localhost';
$dbname = 'mydb';
$username = 'root';
$password = 'password';
try {
// create the connection
$conn = new PDO('mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8', 'root', 'password');
// set the errmode to exception, set this to ERRMODE_SILENT if you want to hide database errors
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage(); // catch any connection errors
$conn = false;
}
$select_data = $conn->prepare("SELECT * FROM search WHERE name LIKE :name OR EmailAddress LIKE :email OR Qualification LIKE :qualification ");
$select_data->bindValue(':name', $name); // bind the values to the paramaters
$select_data->bindValue(':email', $email);
$select_data->bindValue(':qualification', $qualification);
$select_data->execute();
if($select_data->rowcount() > 0){ // rowcount returns the amount of results
// atleast 1 result
$results = $select_data->fetchAll(PDO::FETCH_ASSOC); // fetch the results into an array
foreach($results as $row){
echo 'Name: ' . $row['name'];
echo '<br /> Email: ' . $row['email'];
echo '<br /> Address: ' . $row['address'];
}
}
There are other ways to do this with PDO but this is how I tend to do it.
Please try the below code:
<form id="form" action="" method="POST" >
<fieldset>
<label>First Name </label>
<input type="text" placeholder="Name" value="<?php if (isset($_REQUEST['name'])) echo $_REQUEST['name']; ?>" class="form-control required" id="name" name="name">
<label>EmailAddress</label>
<input type="text" placeholder="EmailAddress" value="<?php if (isset($_REQUEST['EmailAddress'])) echo $_REQUEST['EmailAddress']; ?>" class="form-control required" id="EmailAddress" name="EmailAddress">
<label>Qualification </label>
<input type="text" class="form-control" placeholder="Qualification" value="<?php if (isset($_REQUEST['qualification'])) echo $_REQUEST['qualification']; ?>" id="Qualification" name="Qualification">
<br><input value="Search" name="Search" style="width:100%" type="submit" class="btn btn-success">
</fieldset>
</form>
<?php
if (isset($_POST['Search'])) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("myDB", $con);
if (!$con) {
die("Could not connect: " . mysql_error());
}
$where = '';
if ($_POST['name']) {
$where .="name like '%" . $_POST['name'] . "%'";
}
if ($_POST['EmailAddress']) {
if (!empty($where))
$where.=" or ";
$where .="email like '%" . $_POST['EmailAddress'] . "%'";
}
if ($_POST['Qualification']) {
if (!empty($where))
$where.=" or ";
$where .="qualification like '%" . $_POST['Qualification'] . "%'";
}
$sql = "select id, name, email, qualification from student where " . $where;
echo $sql;
$res = mysql_query($sql) or die("Error in query " . mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
echo "<br><br>";
echo 'No. : ' . $row['id'];
echo '<br /> Name: ' . $row['name'];
echo '<br /> Email: ' . $row['email'];
echo '<br /> Qualification: ' . $row['qualification'];
}
mysql_close($con);
}
?>
I hope this will work for you as you want.

PHP unable to write to MySQL database

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).

Why will it not update to the database?

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>

Categories