I am trying to create a basic form to list inventory on a website using PHP and MySQL. I keep getting errors when I follow some of the guides here on stackoverflow. Any help would be greatly appreciated.
My question is: My insert statement keeps failing when I use it through the PHP form but when I do it through phpMyAdmin it works. How do I figure out where my error is and how do i solve it.
Form:
<form action="add.php" method="post" enctype="multipart/form-data">
Item Type: <input type="text" name="type" /><br>
Description: <input type="text" name="description"/><br>
Price: <input type="text" name="price" /><br>
Date: <input type="text" name="date" /><br>
Pic:<input type="file" name="image"> <br/>
<input type="submit" >
</form>
add.php:
<?php
$type = $_POST['type'];
$desc = $_POST['description'];
$price = $_POST['price'];
$date = $_POST['date'];
$file = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_size = getimagesize ($_FILES['image']['tmp_name']);
$host = "localhost";
$user = "root";
$password = "";
$cnn = mysql_connect ( $host, $user, $password );
mysql_select_db('inventory');
$insert = mysql_query("INSERT INTO 'newitems' ('ID', 'ItemType', 'Description', 'Price', 'Date', 'Pic')VALUES ('','$type','$desc','$price','$date', '{$image}')");
if (!mysql_query($insert)) {
echo "Something went wrong! :(";
echo '<img src="data:image/jpeg;base64,' . base64_encode( $image ) . '" />';
}
?>
Table Updated with Auto-Number
If your ID column in that schema has a UNIQUE constraint, then it's no wonder the query will fail the second time around since you're inserting every row with the same id (4). Use AUTO_INCREMENT instead and let the dbms assign the ID.
Important Information About Your Code
Also, it's probably crucial that you are aware of a number of critical issues in your code.
You are using a deprecated extension for talking to your mysql database
Your code is vulnerable to SQL injection by using addslashes
You really shouldn't be storing images in your database
Reasons why you shouldn't store binary data in your RDBMS
The filesystem is faster/better at storing binary data
You don't have to carry the blob data in PHP to get it to the user saves CPU and memory
Seperate the webhost and the dbhost, moving blobs back and forth over a database connection is going to be expensive in computation and bandwidth
Single point of failure (even with master/slave replication you are going to incur massive replication lag at scale) where there are much cheaper redundancy solutions like a CDN
Related
(so to begin I'm a high school student so not the greatest with the lingo so try your best to guide rather than tell if you can) When using insert to put data into my database from the website it appears to work but nothing appears in the database but no error codes.
I am using Mysqli, PHP, and Wampserver to run a local server and the website will not send data to the Database.
<?php
include 'connect.php';
include 'header.php';
?>
Sign Up<br>
<form method="post" action="">
Username: <input type="text" name="user_name"><br>
password: <input type="password" name="user_pass"><br>
password <Check: input type="password" name="user_pass_check"><br>
Email: <input type="text" name="user_email"><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO users(user_name, user_pass, user_email) VALUES('".mysqli_real_escape_string($con, $_POST['user_name'])."', '".sha1($_POST['user_pass'])."', '".mysqli_real_escape_string($con, $_POST['user_email'])."', NOW(), 0)";
$result = mysqli_query($con, $sql);
if (!$result) {
echo 'Something went wrong';
echo mysqli_error($con);
} else {
echo "you have successfully registered. you can now <a href='signin.php'>sign in</a> and start posting";
}
}
}
include 'footer.php'?>
In my file used for connection
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'seqevents';
$con = new mysqli($host, $user, $pass, $dbname) or die("cannot connect");
session_start();
if (!isset($_SESSION['user_level'])) {
$_SESSION['user_level'] = 0;
}
I receive no error messages and nothing happens on the website it just reloads and gets rid of any input within the text boxes.
First the (likely) problem, then some other important pointers:
When you insert, you insert set 3 columns (user_name,user_pass,user_email) and then load 5 values into it (NOW() and 0) are extra, it has no clue where to place those values.
DO NOT USE MD5. If you're thinking "yeah, but my site isnt very interesting, why cares" read this line again. DO NOT USE MD5. Or sha1:
Never store passwords in clear text or using MD5/SHA1! Only store password hashes. Use PHP's password_hash() and password_verify() . If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality. – Dharman
Use prepared statements. mysqli_real_escape_string is a good first step, but not adequite. Prepared statements secure the query for you. Bit more complex, a lot more secure.
I suggest removing $_SERVER['REQUEST_METHOD'] === 'POST'. What if you have two forms on your page? You're stuck. Instead, give your submit button a name like submitRegForm. Then you can do if( isset($_POST['submitRegForm']) )
DO NOT USE MD5 OR SHA1
Each time i update the database, it create a new row with the new information i was trying to update and a new customerID each time, is there a way to resolve this.
The update query calls two tables Cus_acct_details and cus_register. The query is meant to change cus_email in both tables, and update all the information in cus_acct_details.
PHP
<?php
//$user = $_SESSION["Cus_Email"];
$Cust_ID = $_SESSION["CustomerID"];
if (isset($_POST['Update'])) {
$UpdateFname = $_POST['fname'];
$UpdateLname = $_POST['Lname'];
$UpdateEmail = $_POST['email'];
$UpdatePhone = $_POST['phone'];
}
$sql = $dbc->query("UPDATE Cus_Register, Cus_acc_details
SET Cus_acc_details.CUS_Fname = ' $UpdateFname',
Cus_acc_details.CUS_Lname = ' $UpdateLname',
Cus_acc_details.CUS_Email = ' $UpdateEmail',
Cus_acc_details.Cus_Phone = ' $UpdatePhone',
Cus_Register.CUS_Email = ' $UpdateEmail',
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
WHERE Cus_Register.CustomerID = '$Cust_ID'
");
print_r($_POST);
header('Location: Cus_Account.php');
?>
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo $_SESSION['fname']; ?>" required>
<input type="text" id="lname" name="lname" value="<?php echo $_SESSION['lname']; ?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<input type="number" id="phone" name="phone" value="<?php echo $_SESSION['phone']; ?>" required>
<input type="submit" name="Update" value="Update">
<br>
</form>
The $cust_id variable was defined earlier on.
Where have a gone wrong.
An UPDATE statement won't insert a new row. There must be an INSERT statement running. (1)
The syntax of the update statement looks wrong to me, I'd expect that to be throwing an error.
The ON clause is used with the JOIN keyword, but the old-school comma operator is used for the join operation. The SET clause should be the last thing before the WHERE clause.
UPDATE Cus_Register
JOIN Cus_acc_details
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
SET Cus_acc_details.CUS_Fname = ?
, Cus_acc_details.CUS_Lname = ?
, Cus_acc_details.CUS_Email = ?
, Cus_acc_details.Cus_Phone = ?
, Cus_Register.CUS_Email = ?
WHERE Cus_Register.CustomerID = ?
It seems odd that there's an extra space in the string literals.
Assigning the return from a ->query() to a variable is a common pattern. But naming that variable $sql is very strange.
The normative pattern is to assign the SQL text (a string) to a variable named $sql, and then referencing the variable
$sql = 'SELECT foo FROM bar ORDER BY foo LIMIT 1';
$result = $dbc->query($sql);
Then check the return from query, to see if it was successful, or if an error occurred. If you're using PDO, you can configure the connection to throw an exception, and handle it in a catch block.
If your code doesn't do that, it's putting it's pinky finger to the corner of its mouth Dr. Evil style and saying "I'm just going to assume it all goes to plan. What?"
Also, the code appears to be vulnerable to SQL Injection. If any potentially unsafe values are included in the SQL text, those values must be properly escaped before they are included.
The preferred pattern is not even include the values in the SQL text, but to use prepared statements with bind placeholders, and supply the values through the placeholders.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
(1.) Of course it's possible to define a BEFORE UPDATE and/or an AFTER UPDATE trigger that performs an INSERT. But it's the INSERT statement that inserts the row, even if the firing of the trigger is "caused" by running an UPDATE.
Set CustomerID to be a key and add an ON DUPLIACTE KEY UPDATE clause
I need help for my web service project where user create an order when submit the order form, Driver get notification with accept or reject the order and when he accept order details list display to him. these all process done with order form submission. my all coding working fine. I don't understand where from get id of current order list. plz give solution. thx
<?php
if(isset($_POST['order_form']))
{
mysql_connect('localhost','root','');
mysql_select_db('live_help');
$user = $_POST['user'];
$password = $_POST['mobile'];
$password = $_POST['address'];
$password = $_POST['order_item'];
$password = $_POST['price'];
$sql= mysql_query("insert into `json_web`(user,mobile,address,order_item,price) values('$user','$mobile','$address','$order_item','$price')");
if($sql)
{
echo 'Value Saved';
}
}
?>
<form name="order_form" action="" method="post">
<input type="text" name="user">
<input type="text" name="mobile">
<input type="text" name="address">
<input type="text" name="order_item">
<input type="text" name="price">
<input type="submit" name="field1" value="Submit" />
</form>
use mysql_insert_id(); to grap the last insert id. Take a look for more information
mysql_insert_id()
Warning:
mysql_* is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
After your mysql_query(); you can do this:
$id = mysql_insert_id();
mysql_insert_id(); retrieves the ID of the last inserted element to the database.
Use mysqli_insert_id() as from documentation
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
In order to use mysql_insert_id() you need to add another field into the database table so you can have distinct order id for each order.
Perhaps you already have it, if not, add it:
ALTER TABLE `json_web` ADD order_id INT(10) NOT NULL AUTOINCREMENT;
Then just select from database, use mysql_insert_id()
Cheers
I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.php');
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.
I have a question, I am new to PHP and I have been working on some exercises. The one I am currently working on is to create a simple form that will search a database (first name, last name). The returned results should then be populated into another form. This way, if I want to update the record, all I have to do is change the value of the populated form and hit Update. I have create the database no problem.
The following is the code. (Please don't laugh, I'm very new...I am sure there are much more efficient ways of doing this, but I'm just playing around right now)
Here is the form:
<form action="" method="post">
<strong>Search for name</strong><br>
<label for="fname">First Name</label>
<input type="text" name="fname">
<label for="lname">Last Name</label>
<input type="text" name="lname">
<input type="submit" name="submit" value="Search">
</form>
And here is the PHP:
if( isset( $_POST['submit'] ) ){
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
if ( $first_name == NULL || $last_name == NULL ) {
echo "please enter search record";
}
else {
$query = "SELECT first_name, last_name FROM formdata WHERE first_name LIKE '%$first_name%' OR last_name LIKE '%$last_name%'";
$result = mysqli_query( $conn, $query );
$result_array = mysqli_fetch_row( $result );
$fname_value = $result_array[0];
$lname_value = $result_array[1];
echo "
<form action='' method='post'>\n
<label for='fname_u'>First Name</label>\n
<input type='text' name='fname_u' value='$fname_value'>\n
<label for='lname_u'>Last Name</label>\n
<input type='text' name='lname_u' value='$lname_value'>\n
<input type='submit' name='update' value='Update'>\n
</form>";
}
}
if( isset( $_POST['update'] ) ) {
$first_name_u = ( $_POST['fname_u'] );
$last_name_u = ( $_POST['lname_u'] );
$query_update = "UPDATE formdata SET first_name = '$first_name_u', last_name = '$last_name_u' WHERE first_name = '$fname_value';";
echo $query_update; // this is just for testing
}
This code seems to work and do what I want, all the way up to when I submit the updated information. I can't figure out how to carry over the value of the $fname_value variable to the if( isset( $_POST['update'] ) ) conditional. I am thinking I can't because they are two different POSTS? I really don't know...I just need to find a way to get value of the retrieved form data and use for the WHERE clause.
Again, I'm very new and just getting my feet wet with this kind of stuff ... Any help would be great
Thanks
I think you have a typo in your code. Your POST data is saved to the variable $first_name, but when you query SQL you are using $first_name_r instead of $first_name.
I'm thinking the typo is the answer, but I have to point out one deadly mistake you've made, and that is that you're piping user-supplied input directly into an SQL query. This opens your code to a slew of malicious attacks called SQL injection attacks. I'm not trying to be preachy, but it's very important that you read and understand that article, especially the part about Mitigation at the bottom.
I would suggest you use something like this instead:
$query = 'SELECT first_name, last_name '.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = mysqli_prepare($dbh, $query);
mysqli_stmt_bind_param($sth, "s", '%'.$first_name.'%');
mysqli_stmt_bind_param($sth, "s", '%'.$last_name.'%');
$result = mysqli_execute($sth);
I know it's a bit longer and more complicated, but trust me, it will save you a world of headache. The sooner you learn about this and get it deeply ingrained in your psyche that you can never, ever, ever write a query that passes unsanitized input straight to the database, the happier we all will be (and the longer you will get to keep your job eventually. ;).
Sorry if I'm coming on strong, but in my opinion, the single most important lesson you need to pick up early in developing database-driven web sites is that you really need to be proficient at spotting injection vulnerabilities to the point where it's automatic and when you see it, you think, "Ooh! Noooo! Don't do that!!!"
Above answer found your isssue, but on a sidenote:
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
Do not do this. That my friend is the most common security vulnerability for php applications.
The most 2 most important things to remember when scripting is
Filter input, and
2: Escape output.
See this write-up for more details ..
In your case, the input values are not filtered, or checked for malicious/improper values.
Here is another primer on this page to see a few tips and how to address filtering.
Keep it up, those exercises are a fine way of picking up chops.
Happy coding friend.
Okay, re-reading your post, I think I see what you're trying to do and where you're having difficulty. Normally, you won't have two separate pages for one identical form like this. Typically, you'll code it more along these lines, and please keep in mind that I'm winging this off the top of my head, not actually testing it, so minor corrections and/or tweakage may be required:
<?php
$fname_value = '';
$lname_value = '';
if (isset($_POST['submit']) && $_POST['submit'] === 'Search') {
if (isset($_POST['fname']) && isset($_POST['lname'])) {
// We are processing a submitted form, not displaying a brand new one
// from scratch. Code any post-validation steps.
// Fetch the user information from the database. You'll need to define
// the $host, $user, $password, and $dbname variables above, or
// substitute literal strings with real information in here.
$dbh = new mysqli($host, $user, $password, $dbname);
$sql = 'SELECT first_name, last_name'.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = $dbh->prepare($sql); // Use parameters to avoid injection!
$sth->bind_param('s', $_POST['fname']);
$sth->bind_param('s', $_POST['lname']);
if ($sth->execute()) {
$result = $sth->get_result();
if (($row = $result->fetch_assoc()) != NULL) {
// Set the default values displayed in the text edit fields.
$fname_value = $row['first_name'];
$lname_value = $row['last_name'];
}
}
// Whatever other processing you want to do if this is a submitted
// form instead of displaying the page from scratch.
}
}
?>
<html>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<strong>Search for name</strong><br />
<label for="fname">First Name</label>
<input type="text" name="fname" value="<?= htmlentities($fname_value) ?>">
<label for="lname">Last Name</label>
<input type="text" name="lname" value="<?= htmlentities($lname_value) ?>">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>