How do I add a row to mySQL using PHP? - php

I am trying to add an "admin" section of my website. Right now I am working on a section to add a new row to my MySQL database.
The first file is my admin.php:
<html>
...
<body>
<form action="add.php" method="post">
<input type="text" name="order" />
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
</body>
</html>
My goal here is to add 2 pieces of data (the table only has 2 columns right now) to the new row.
Then, I have my add.php file:
<?
//declare my connection variables - I'll move these to a secure method later
mysql_connect($servername, $username, $password) or die (mysql_error ());
// Select database
mysql_select_db($dbname) or die(mysql_error());
// The SQL statement is built
$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='admin.php'>Back to main page</a>";
}
else {
echo mysqli_errno($this->db_link);
}
?>
<?php
// close connection
mysql_close();
?>
Anytime i input any data (non-duplicate of what is already in the table), it gives me an error. If I clear my table completely of all data, it will input once. I am getting a duplicate key error, but my key should be "orders", which is unique every time I input it.
Suggestions?

If you are actually inserting a new row, you shouldn't fill the ID yourself but rather set it as AUTO_INCREMENT in your database. And then, have you form as such:
<form action="add.php" method="post">
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
And your PHP code like so:
$newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable
$sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')";
$result = mysql_query($sql) or die('Failed executing query: '.mysql_error());
AUTO_INCREMENT can be set up in phpMyAdmin with the following query:
ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT;
Finally, don't use mysql_* functions, they are deprecated.

I am guessing the 'id' field of your table is a primary key. If that's the case, you cannot have two rows that have the same identifier.
By your variable name newstatus, it seems to me like you're trying to update the status of an order ; is it the case? If yes, you should use a UPDATE SQL query of the form:
UPDATE table SET status='somestatus' WHERE id=someid

Related

Form Data Gets Inserted Into MySQL Table But Still Server Throws Error

I want to insert some values into my book table and I created a PHP page with HTML form inside it. The problem is my values gets inserted but it throws a primary key error on the webpage. The code is as below.
<!DOCTYPE html>
<html>
<head>
<title>New Books</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$server="localhost";
$username="root";
$password="";
$db="library";
$conn= new mysqli($server,$username,$password,$db);
if ($conn->connect_error) {
echo "Server Error Occured Please Try Again Later";
}
$bid=$_POST['bid'];
$bname=$_POST['bname'];
$baut=$_POST['baut'];
$bc=$_POST['bc'];
$blf=$_POST['blf'];
$bs=$_POST['bs'];
$sql="insert into books(BOOK_ID,BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE, BOOK_STATUS) values('$bid','$bname','$baut','$bc','$blf','$bs')";
$result=$conn->query($sql);
if ($conn->query($sql)===TRUE) {
echo "New Book Added Successfully";
}
else{
echo "Please Recheck The Values Entered" . $conn->error;
$secondsWait = 5;
header("Refresh:$secondsWait");
}
}
?>
<div class="header">
Lowa State University
<div class="header-right">
<a class="active" href="#">Main Page</a>
Due Fines
Contact Us
Profile
</div>
</div>
<form action="" method="post">
<input type="text" name="bid" placeholder="BOOK ID"><br><br>
<input type="text" name="bname" placeholder="BOOK NAME"><br><br>
<input type="text" name="baut" placeholder="BOOK AUTHOR"><br><br>
<input type="text" name="bc" placeholder="BOOK CATEGORY"><br><br>
<input type="number" name="blf" placeholder="BOOK LOST FINE"><br><br>
<input type="text" name="bs" placeholder="BOOK STATUS"><br><br>
<input type="submit" name="submit" value="Add Book"><br><br>
<input type="reset" name="reset" value="Clear Fields">
</form>
</body>
</html>
SAMPLE VALUES IN FORM
Now if I press the add button this error shows up:
Error Image:
but the values are already entered into the SQL table.
When you add any field as primary key that mean it must have unique record, no duplication allowed. you trying to add duplicate(same record) in same table.
You should add BOOK_ID as primary key + auto increment in database and when you insert new record, you don't need to add BOOK_ID manually at code. i automatically incremented from previous record and added automatically.
Just do like this
$sql="insert into
books(BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE,
BOOK_STATUS) values('$bname','$baut','$bc','$blf','$bs')";
and remove following line $result=$conn->query($sql);
Note [add BOOK_ID AS PRIMARY KEY + AUTO INCREMENT in Table]
Just like hingu Devang and Bira mentioned, make your ID column Auto_Increment and do not manually place a value there because it will automatically assign a value.
As for your issue that the query is being executed twice, try removing the line:
$result=$conn->query($sql);
Because you already have a query which is:
if($conn->query($sql)===TRUE)

If input exists from one table update it on another one

Im trying to make like a refill code that will refill my table.
I have one table that have my refill code in it and other table that stores the balance of the account.
table1: card_credit (table that stores the balance of the account)
table2:card_refill (table that have me refill code)
I have created this code with session and PHP. Now I'm stuck and dont know how to move forward.
I want to make when i write in the refill code from table card_refill that its take the amount of credit into value in table card_refill
refill.php
<strong>Refill</strong>
<form action="refill.php" method"post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['refillcode'] = $_POST['refillcode'];
}
?>
Here is a possible solution, I am just don't know, where the card_id comes from.
This is inserting a new record into your card_credit table.
// starting the session before any output
session_start();
//include here the database connection file!
//for example:
//include('db_connection.php');
if (isset($_POST['Submit'])) {
//First do a validation here, is the refillcode number, exists, etc...
//Insert it into the table
$sql = "INSERT INTO card_credit (card_id, value) VALUES ('[YOUR_CARD_ID_HERE]', " . intval($_POST['refillcode']) . ")";
//Link is the resource variable when you created the mysqli_connect
mysqli_query($link, $sql);
//Redirect here if you want
}
?>
<!-- HTML CODE STARTS HERE -->
<strong>Refill</strong>
<form action="refill.php" method="post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>

Updating database based on certain ID

I have a table within my database containing subscriptions, each subscription has a name, id and a notes column.
I'm trying to allow the user to update the notes column through a text area on the webpage. All of the subscriptions are in a list on the page which allows the user to click on them to view that specific subscription.
How would I make sure the note that is updated is correct with the id of the subscription they have clicked on?
I currently have this code.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="submit" name="submit"/>
</form>
This is what I think my noteAction.php should look like however I cannot get it working.
mysql_connect ("host", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("database_name") or die ('Data error:' . mysql_error());
$text = mysql_real_escape_string($_POST['noteValue']);
$query="UPDATE `subscription` SET `notes`= '$text' WHERE `id` = '$id'";
mysql_query($query) or die ('Error updating database ' . mysql_error());
Any help would be great, thanks.
Use hidden element to store your id inside it.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="hidden" name="id" value="id" value="your id goes here" />
<input type="submit" name="submit"/>
</form>
When you're putting the note in the form, you must have an id for that note kicking about somewhere, after you retrieved it from the database. If you only selected the note contents in that query, select the ID as well. Then pass the ID over in a hidden field, and you have the ID to use in the MySQL query (which is correct).
<input type="hidden" name="note-id" value="note_id_here">

Creating table and adding data to it is not working

Well I am pretty much trying to create database with some table, the values in the table and check them in phpMyAdmin. I am able to create the table and database, but not the values
2.) when I add the isset $_post['submit'] variable, when I click the submit button, nothing is getting created. Is there a syntax error I am not seeing?
<html>
<body>
<p> welcome to my Page
Please insert the data below
<br>
<br>
<form action="input.php" method="post">
<p> Name: <input type="text" name="name">
<p> Age: <input type="text" name="age">
<p> Address: <input type="text" name="address">
<p> Email: <input type="text" name="email">
<input type="submit" value="Send!" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
//connects to the sql database
$con = mysql_connect("localhost", "willc86", "tigers330");
if (!$con) {
echo 'can not connect to Database' . "<br>";
}
//creates the database in mySQL
$db = mysql_query("CREATE DATABASE form");
if (!$db) {
echo 'Did not create database';
}
//select the database and connect to it. on where you want to create tables.
mysql_select_db("form", $con);
//create the table once "form database" is selected
$table = "CREATE TABLE users (
Name varchar(30),
Age varchar(30),
Address varchar(30),
Email varchar(30)
)";
mysql_query($table,$con);
//insert the data from the form
$value= "INSERT INTO users (Name, Age, Address, Email)
VALUES ('$_POST[name]','$_POST[age]','$_POST[address]','$_POST[email]')";
mysql_query($value,$con);
mysql_close();
}//end of submit
?>
</body>
</html>
Your form action is input.php, is your file called input.php as well? Otherwise you'd be executing input.php when you're submitting the form instead of executing the PHP on your page.
I think user willc86 don't have access rights for create databases.
In second your script is incorrect, because it run for each "user add" operation and tried create database and table.
You can create it once in phpadmin and use in your script only insert.
No point in highlighting particular errors here as others are unlikely to have the exact same issue. Better to just give you the tools/means to debug the issue for yourself.
Instead of:
mysql_query($table,$con);
Try:
$res = mysql_query($table,$con);
if($res === false){
throw new Exception(mysql_error($conn));
}
Better yet, use PDO.
First of all your code is fine if this file name is input.php. There can be few reasons, one that you have incorrect credentials second that the user does not have a right to create table, for that go to Phpmyadmin and give user all rights.
Secondly and most importantly, use Prepared statements or mysqli otherwise you are vulnerable to SQL Injection
For that do go through this post
How can I prevent SQL injection in PHP?

How can I check if a MySql field is equal to 1?

I'm creating a forum in PHP and using MySql as a database, and was wondering how I could check if a MySql field topic_locked was equal to 1. If it isn't, the reply code would be displayed. How can I check this, and if you can help me find how to check this, how could I set it to 1 through the forum?
I dont know your code. But I am sharing simple program to check a mysql field's value.
<?php
// Database select and connect to host
$sql= mysql_query("SELECT topic_locked FROM table WHERE Id='your_id'");
$res= mysql_fetch_array($sql);
$value= $res['topic_locked'];
if($value=='1')
{
// reply code
}
?>
Update asked,
<?php
if(isset($_POST['update']))
{
$id= $_POST['id'];
//Database select and connect to host
mysql_query("UPDATE table SET topic_locked='1' WHERE Id='$id'");
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="your_id" />
<input type="submit" name="update" />
</form>

Categories