Cannot insert lines into database - php

I have a basic database that consists of three tables :
Product(idP,name,price,quantity,stock_Minimal,stock_maximal)
Order(ref,date)
Order_Line(idP,ref,quatity)
the product table contains a catalogue of all the product available, the order table contains a list of all the orders references and their respective dates,and finally the order_line table contains informations about whats been ordered in every command
here is the code that I use to insert an order into the order table and its lines to Order_Line table:
<?php
if (isset($_POST['ref'])) {
$ref = $_POST['ref'];
$date = $_POST['date'];
$choosed_product = $_POST['choosed_product'];
$quantity = $_POST['quantity'];
$cn = mysqli_connect("localhost", "root", "");
mysqli_select_db($cn, "vente_db");
$res = mysqli_query($cn, "select * from commande where ref=" . $ref);
$cn->close();
if ($res != null) {
$cn->query("insert into Order_Line values (" . $choosed_product . ",$ref,$quantity)");
} else {
$co = mysqli_connect("localhost", "root", "");
mysqli_select_db($co, "vente_db");
mysqli_query($co, "insert into Commande
values('$ref',''$date'')");
mysqli_query($co, "insert into Order_Line values
(" . $choosed_product . ",$ref,$quantity)");
}
}
?>
But when I check the databse I don't find the inserted lines,can you please help me figure out the problem in my code
[edit]:I know that my code is vulnerable to sql injections, but this is just for a school project and we're not required to secure the database against hackers.

There are a lot of issues with this code. Your code is very much vulnerable to SQL Injection Attacks! I have commented everything inside the code:
Put connection string in the first line for making it available to use.
Add the DB selector to the connection.
Give an alternate message if connection fails.
Make sure you sanitize the data.
Optional: Make sure you backtick the column names and add single quotes for values.
This is not needed here. $cn->close();
Make sure you use the same implementation. Either OOP or Procedural.
You don't need another connection. $co = mysqli_connect("localhost", "root", ""); mysqli_select_db($co, "vente_db"); Use the previous connection.
You have an error in the SQL Syntax with double single quotes.
Add single quotes for the values.
Corrected Code:
<?php
if (isset($_POST['ref'])) {
// Put connection string in the first line for making it available to use.
// Add the DB selector to the connection.
// Give an alternate message if connection fails.
$cn = mysqli_connect("localhost", "root", "", "vente_db") or die("Cannot Connect. " . mysqli_connect_error());
// Make sure you sanitize the data.
$ref = mysqli_real_escape_string($cn, $_POST['ref']);
$date = mysqli_real_escape_string($cn, $_POST['date']);
$choosed_product = mysqli_real_escape_string($cn, $_POST['choosed_product']);
$quantity = mysqli_real_escape_string($cn, $_POST['quantity']);
// Optional: Make sure you backtick the column names and add single quotes for values.
$res = mysqli_query($cn, "select * from `commande` where `ref`='" . $ref . "'");
// This is not needed here.
// $cn->close();
if ($res != null) {
// Make sure you use the same implementation. Either OOP or Procedural.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
} else {
// You don't need another connection.
// $co = mysqli_connect("localhost", "root", "");
// mysqli_select_db($co, "vente_db");
// Use the previous connection.
// You have an error in the SQL Syntax with double single quotes.
mysqli_query($cn, "insert into `Commande` values('$ref', '$date')");
// Add single quotes for the values.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
}
}
?>
This should probably work. If not, at least it would tell you why it failed.

Related

PHP SQL syntax error MYSQL UPDATE [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
So for a long time this code worked but now all of the sudden i get this error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''j_users' SET patient = '', year = '', gender = '', age = '', height = 'Select a' at line 1
HELP!
define('DB_NAME', 'DATABASE');
define('DB_USER', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = htmlspecialchars($_POST['patient']);
$value4 = htmlspecialchars($_POST['year']);
$value5 = htmlspecialchars($_POST['gender']);
$value6 = htmlspecialchars($_POST['age']);
$value7 = htmlspecialchars($_POST['height']) . '.' . htmlspecialchars($_POST['height_inch']);
$value8 = htmlspecialchars($_POST['weight']);
$value9 = htmlspecialchars($_POST['foot_length']);
$value10 = htmlspecialchars($_POST['sheight']) . '.' . htmlspecialchars($_POST['sheight1']);
$value11 = htmlspecialchars($_POST['Amputation']);
$value13 = htmlspecialchars($_POST['Side']);
$value16 = htmlspecialchars($_POST['Flesh']);
$value18 = htmlspecialchars($_POST['Activity']);
$value21 = htmlspecialchars($_POST['practitioner']);
$value22 = htmlspecialchars($_POST['phone']);
$value23 = htmlspecialchars($_POST['email']);
$value24 = htmlspecialchars($_POST['Account']);
$value25 = htmlspecialchars($_POST['companyname']);
$value26 = htmlspecialchars($_POST['streetaddress']);
$value27 = htmlspecialchars($_POST['city']);
$value28 = htmlspecialchars($_POST['state']);
$value29 = htmlspecialchars($_POST['zip']);
$value30 = htmlspecialchars($_POST['companyname2']);
$value31 = htmlspecialchars($_POST['streetadress2']);
$value32 = htmlspecialchars($_POST['city2']);
$value33 = htmlspecialchars($_POST['state2']);
$value34 = htmlspecialchars($_POST['zip2']);
$value35 = htmlspecialchars($_POST['foot']);
$value39 = htmlspecialchars($_POST['purchaseorder']);
$value40 = htmlspecialchars($_POST['radio']);
$value41 = htmlspecialchars($_POST['lightflesh2']);
$value42 = htmlspecialchars($_POST['darkfleah2']);
$value43 = htmlspecialchars($_POST['foamcalf']);
$value44 = htmlspecialchars($_POST['additional']);
$value45 = htmlspecialchars($_POST['Sock1']);
$value46 = htmlspecialchars($_POST['Sock2']);
$value47 = htmlspecialchars($_POST['Sock3']);
$value48 = htmlspecialchars($_POST['day']);
//$sql = "INSERT INTO order_form (patient, newamputee, yearamputee, year, gender, age, height, weight, foot_length, sheight, ak, bk, left1, right1, bilateral, light_flesh, dark_flesh, k2, k3, k4, k4_extrme, practitioner, email, Account, companyname, streetaddress, city, state, zip, companyname2, streetaddress2, city2, state2, zip2, UltraStride, ActiveStride, NaturalStride, K2_ComfortStride, purchaseorder, radio, lightflesh2, darkfleah2, foamcalf, additional, Sock1, Sock2, Sock3, ground, thirdday, twoday, nextday) VALUES ('$value', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9', '$value10', '$value11', '$value12', '$value13', '$value14', '$value15', '$value16', '$value17', '$value18', '$value19', '$value20', '$value21', '$value22', '$value23', '$value24', '$value25', '$value26', '$value27', '$value28', '$value29', '$value30', '$value31', '$value32', '$value33', '$value34', '$value35', '$value36', '$value37', '$value38', '$value39', '$value40', '$value41', '$value42', '$value43', '$value44', '$value45', '$value46', '$value47', '$value48', '$value49', '$value50', '$value51')";
$update = "UPDATE 'j_users'
SET patient = '$value', year = '$value4', gender = '$value5', age = '$value6', height = '$value7', weight = '$value8', foot_length = '$value9', sheight = '$value10', Amputation = '$value11', Side = '$value13', Flesh = '$value16', Activity = '$value18', practitioner='$value21', phone='$value22', email='$value23', Account = '$value24', companyname = '$value25', streetadress='$value26', city='$value27', state='$value28', zip='$value29', companyname2='$value30', streetadress2='$value31', city2='$value32', state2='$value33', zip2='$value34', foot='$value35', purchaseorder='$value39', radio='$value40', lightflesh2='$value41', darkfleah2='$value42', foamcalf='$value43', foamcalf='$value44', Sock1='$value45', Sock2='$value45', Sock3='$value46', day='$value47'
WHERE user_login = '" . $user . "'";
if (!$update) {
die('Invalid query: ' . mysql_error());
}
mysql_query($update, $link);
if (!mysql_query($update)) {
die('Error: ' . mysql_error()) ;
mysql_close();
}
The immediate cause of the error, as pointed out by Uueerdo in the comment is the incorrect symbol (single-quote instead of a backtick) in the quoting of the name of the table - which in this case does not need to be quoted at all as it is fixed and contains no special characters.
There are other issues in the code which we will leave alone for now as they do not immediately affect the issue, but I will update the answer if OP is interested in other things that would be good to fix.
UPDATE - things to fix:
As pointed out by Drew and Uueerdo in the comments, migrate from the deprecated mysql_ interface to mysqli_ or PDO.
The values entered by the user should be escaped with mysql_real_escape_string() (with the current interface), mysqli_escape_string() or via PDO parameter holders (?) depending on the interface, but not with htmlspecialchars(). If HTML escaping is needed, it should be done immediately before the HTML is to be displayed, not at the time it is stored in the database.
Note that most of your input names match the database column names. Thus you might be better off fetching the fields from the database via SHOW FIELDS once into a hard-coded array, editing it to exclude the irrelevant ones (another option to fetch it dynamically and fix up the array once it is fetched), and adding some logic to deal with the exceptions like height and height_inches as you iterate through the array and generate your query in a loop. The code thus becomes more flexible and easier to maintain.
Create some wrapper interface for your database access rather than directly accessing MySQL API. This way should a need arise to change the interface (e.g. mysql_ to mysqli) it is a matter of fixing a few calls in just one module rather than a major code change. You are also able to add things like query logging, automatic query EXPLAIN in trace mode, performance timing, and whatever else you might think of with regard to your queries, rather easy.

SQL Update code issue/PHP injection

I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";

Return the id of the last MySQL insert in PHP

I'm trying to grab the id of the last inserted auto-increment row and cannot successfully grab it.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$title = mysqli_real_escape_string($conxn,$_POST['blog_title']);
$entry = mysqli_real_escape_string($conxn,$_POST['blog_entry']);
$sourceName = mysqli_real_escape_string($conxn,$_POST['blog_source_name']);
$sourceLink = mysqli_real_escape_string($conxn,$_POST['blog_source_link']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$title','$entry','$sourceName','$sourceLink')";
$lastID = $mysqli->insert_id;
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
When I echo $lastID a "0" is returned after every submit.
You need to place the $mysqli->insert_id() after the actual mysqli_query(). See below.
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
$lastID = $mysqli->insert_id;
That said, there are other issues with your code. First & foremost, you are mixing up the Object oriented style of calling mysqli_* with the procedural style. For example the OOP method of $mysqli->real_escape_string equates to the procedural method of mysqli_real_escape_string.
So this:
$lastID = $mysqli->insert_id;
Should be this:
$lastID = mysqli_insert_id($conxn);
So without seeing the rest of your code, unclear how to handle. Know the difference & experiment. But here are my suggestions in good faith based on the code you have presented.
For example, your references to $_POST values do not have single quotes, so I added that. Also, since you are using double quotes—which handle string substitution—you can condense your INSERT variable setting by getting rid of the . concatenation.
$title = mysqli_real_escape_string($conxn, $_POST['blog_title']);
$entry = mysqli_real_escape_string($conxn, $_POST['blog_entry']);
$sourceName = mysqli_real_escape_string($conxn, $_POST['blog_source_name']);
$sourceLink = mysqli_real_escape_string($conxn, $_POST['blog_source_link']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$title','$entry','$sourceName','$sourceLink')";
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
$lastID = mysqli_insert_id($conxn);
That done, this code chunklet can be cleaned up even more, and this is how I would handle it. I have made an array of the $_POST values you are grabbing so you don’t have to repeat code. Also added comments to make it clearer what is happening. And I have used the procedural format for all commands here. If OOP is what you want, then you need to change all of the commands to match OOP format.
// Set all of the `$_POST` values into an array.
$post_items = array('blog_title','blog_entry','blog_source_name', 'blog_source_link');
// Roll through those values with a `foreach` loop.
foreach ($post_items as $post_item) {
$$post_item = mysqli_real_escape_string($conxn, $_POST[$post_item]);
}
// MySQL connection error check.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the SQL values.
$sql = "INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$blog_title','$blog_entry','$blog_source_name','$blog_source_link')";
// Run the query.
if (!$mysqli_query($conxn, $sql)) {
die('Error: ' . mysqli_error($conxn));
}
// Get the last insert ID via object oriented method.
// $lastID = $mysqli->insert_id;
// Get the last insert ID via procedural method.
$lastID = mysqli_insert_id($conxn);

Beginner MySQL database search - not getting results

I am having my first attempts to a search engine:
I have a database called "global" and a table called "mpl" which contains 11 columns (Named: Customer, Part No, Descripton, Country Of Origin, and several other) with multiple rows for parts.
What i aim to do with the code below - is to get the Description and Country Of Origin displayed for the Part No the user has entered to the search field.
Form:
<form action="search.php" method="post">
<input type="text" name="find" /><br />
<input type="submit" value="Search" /> </form>
And the PHP:
$host = "localhost";
$dbuser = "root";
$dbpass = " ";
$db = "global";
$con = mysql_connect($host, $dbuser, $dbpass);
if(!$con){ die(mysql_error());
}
$select = mysql_select_db($db, $con);
if(!$select){ die(mysql_error());
}
$item = $_REQUEST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
while($row = mysql_fetch_array($data)){
echo $row['Description']. "<br>";
echo $row['Country Of Origin']. "<br><p>";
}
?>
Can someone tell me what am i doing wrong? Once i enter anything to my form 'find' - i get no results. If i run the search using LIKE instead of "=" with no value - it displays a bunch of Descriptions and Country of origin - this means i have connected to my DB correctly. This is driving me nuts..I feel i have messed up the mysql_query() part somehow - but i can't figure out which part.
You are using the wrong characters to escape the Part No column name in your query. Escape them with the backticks (`) and it should be fine.
$data = mysql_query("SELECT * FROM mpl WHERE `Part No` ='".$item."'");
Also, you should validate the user's query to prevent SQL injection.
A lot of people here have already pointed out possible and actual errors in your code, but here's the combined solution. Firstly I converted your code to mysqli which is the correct way of connecting to a mySQL database. The way you were connecting is out of date, and not recommended. Secondly I added some code to stop sql injection. Thirdly, I changed 'Part No' to `Part No``(ignore the second back tick) in your query.
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'global');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$item = $mysqli->real_escape_string($_POST['find']);
/* query database */
$result = $mysqli->query("SELECT * FROM `mpl` WHERE `Part No` = '".$item."'");
while ($col = $result->fetch_array(MYSQLI_ASSOC))
echo '<p>' . $col['Description'] . '<br />' . $col['Country Of Origin'] . '</p>';
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
What if you change:
$item = $_REQUEST['find'];
to
$item = $_POST['find'];
Also some function like mysql_select_db() are deprecated and going to be removed. See:
http://php.net/manual/en/function.mysql-select-db.php
Try changing this potion.
$item = $_REQUEST['find']; $data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
to this
$item = $_POST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE Part No ='$item'");
do something like this in your request to remove any possible whitespaces and normalize to upper case for select string.
$item = strtoupper(trim($_REQUEST['find']));
And do this in your SQL: to normalize as well.
$data = mysql_query("SELECT * FROM mpl WHERE UPPER(TRIM('Part No')) ='".$item."'");
You are basically not getting an exact match on your where clause
First off, I agree with Quentin; you should be using a database API like PDO or Mysqli. Secondly, it looks like people can search for parts by their part numbers or descriptions. Assuming the part numbers are numeric and the descriptions are strings... check the type of input and run the query accordingly.
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "global";
// Establish a database connection and select one.
// Try using one of the database API's.
// Then compose your sql by checking for the type of input from the form.
// Since your request method is a POST, then just look in the `_POST` superglobal.
$item = $_POST['find'];
if( is_numeric($item) ){
$sql = "SELECT * FROM mpl WHERE 'Part No' = {$item}";
}else{
$sql = "SELECT * FROM mpl WHERE 'Description' LIKE '%{$item}%'";
}
// Then perform the query.

PHP attempt to update a MySQL database doesn't update anything

I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()

Categories