Column NOT NULL but script is still creating a row - php

I have a script, which I use to INSERT data to my database. In HTML I have multiple textboxes. If data is entered into the textbox my script is running the INSERT statement. My script is also running the INSERT statement if there is no data entered into the textbox.
If there is no data entered into the textbox, the script creates an empty row in the database. I have tried to block this by changing the column to NOT NULL.
But it seems to be not working.
Does someone know the reason for that and how I can solve it?
Edit 1:
$sql1 = "SELECT * FROM product WHERE id='" . $id1 . "' AND user_id='" . $_SESSION['USER_ID'] . "'";
$result1 = $link->query($sql1);
if ($result1->num_rows > 0) {
$sql11 = "UPDATE product SET voorraad = quantity -" . $quantity . " WHERE user_id='" . $_SESSION['USER_ID'] . "' AND id='" . $id1 . "'";
if(mysqli_query($link, $sql11)){
echo '<p>product1 is updated</p><br />';
} else {
echo '<p>error</p>';
}
} else {
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}
}

You are inserting empty strings, and empty string are not NULL, to check for NULL error do:
INSERT INTO addresses (street, city, state, zip) VALUES (NULL, NULL, NULL, NULL);
and you will see error. The NOT NULL checks only for values that are not NULL.
To prevent empty string either you have to use triggers, or do the checks on server side programming language to convert empty strings to NULL before performing INSERT query. An example trigger for INSERT may be like: (this is just an example)
CREATE TRIGGER avoid_empty
BEFORE INSERT ON addresses
FOR EACH ROW
BEGIN
IF street = '' THEN SET street = NULL END IF;
END;

you can verify variables and execute query if variable is not null & empty ,else write values are null, must pass data

Related

How do I insert a variable into this oci_parse statement

I'm creating PHP code for a web form that sends an automated email after submission, I want to add all the form inputs to an Oracle database.
How do add a variable into my oci_parse statement? for example, how do I pass my $name var into this statement?
I have tried researching the documentation as well as different code.
<?php
if (!empty($name) || !empty($studentemail) || !empty($programofstudy) || !empty($enrolledinanonlineprogram)) {
// create new cnnection (Table name is "register" for sql database)
$db = oci_new_connect("someuser", "somepassword", "somehost");
if (!$db) {
echo "connection error check your server config";
}
else {
echo "Connection sucessful";
}
$name = $_POST['name'];
$studentemail = $_POST['studentemail'];
$programofstudy = $_POST['programofstudy'];
$enrolledinanonlineprogram = $_POST['enrolledinanonlineprogram'];
$bodytext = $_POST['bodytext'];
$stid = oci_parse($db, 'SELECT * FROM register');
$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES (12345)');
oci_execute($stid);
echo "we inserted 12345";
}
?>
The code works and "12345" is inserted into a table in the database however I want to pass in a variable into the oci_parse statement, ​not the hardcoded value.
$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES ('.$variable.')');
OR
$stid = oci_parse($db, "INSERT INTO register (column1) VALUES ($variable)");
//notice the double quotes
If an array or object
$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES ('.json_encode($variable).')');
Be aware of SQL injection, do not append values "as is" to SQL code.
Just imagine a situation
$stid = oci_parse($db,
"UPDATE my_password_table SET password = '$user_input_password' WHERE login = '$user_input_login'");
When user put something like ' or 1 = 1 or '' = ' into $user_input_login field, it makes all passwords to be updated.
Do not trust ANY data you get from a user. Even if you know the user is not able to type that text in that field.
So, the less wrong way to add value into a query is to replace all single quotes into double
$stid = oci_parse($db,
'INSERT INTO register (email) VALUES ('
. str_replace("'", "''", $studentemail) . ' )');
But the right way to do that is use [oci_bind_by_name][1] function
First, you declare bind variables by adding : before the name. Next, you bind the variable to that names
$stid = oci_parse($db, 'INSERT INTO register (email) VALUES (:EMAIL)');
oci_bind_array_by_name($stid, 'EMAIL', $studentemail);
oci_execute($stid);
Note, no quotes required to put string variables.
Also, be careful: this function does not assign the value. It sets up a link between the php variable and name in the query. The value of the variable is taken when oci_execute is performed. That means if you update the variable after it was bound but before query executed, the new value will be applied
$stid = oci_parse($db, 'INSERT INTO register (email) VALUES (:EMAIL)');
$studentemal = 'ABC';
oci_bind_array_by_name($stid, 'EMAIL', $studentemail);
$studentemal = 'XYZ';
oci_execute($stid); // XYZ value is inserted

Change an Insert statement to an update statement in PHP/MySQL

I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
EDIT
The fixed code is below, it now updates records already in the database rather than adding new data.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement
secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE
for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date
Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer
$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");
$stmt = $mysqliConn->prepare("insert into patients
(patient_name, check_in_date, room_number, bed_number, notes)
values (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE notes=values(notes)");
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
mysqli_stmt_bind_param($stmt, "sdiis",
$patient_name, $check_in_date, $room_number, $bed_number, $notes);
hope this helps
Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above
if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017' , 413 , 2 , 'patient is sick'
and record two is
'jane doe' , '3/1/2017' , 413 , 2 , 'patient has wound'
these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following
DROP the Constraint
ALTER TABLE `patients` DROP INDEX `unique_index`;
Then recreate the constraint like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
also if you named your constraint something other than unique_index you can find the key_name by running the following
SHOW INDEX FROM `patients`;
the name will be in the key_name column
additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number
ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
Also, you should really take a look at using PDO with prepared statements and parameters.
https://secure.php.net/manual/en/pdo.prepare.php
Actually I was looking for a small function that converts an INSERT MySQL query to an UPDATE query. So maybe other people were looking for the same and I think this is what the original poster was looking for aswell... I couldnt find any so I made this simple function which works for my needs, ofcourse you will have to make sure your original query is safe from MySQL injection.
It will convert
INSERT INTO aaa (bbb, ccc) VALUES ('111', '222')
to
UPDATE aaa SET ccc='222' WHERE bbb='111'
Use the 2nd variable ($iColumn) to identify the WHERE statement.
function convertInsertToUpdate($sQuery, $iColumn = 1) {
$sNewQuery = "";
$iPos = strpos($sQuery, ' (');
$sTmpTable = substr($sQuery, 0, $iPos);
$iPos = strpos($sTmpTable, 'INSERT INTO ');
$sTmpTable = substr($sTmpTable, $iPos+12);
$iPos = strpos($sQuery, ') VALUES (');
$sTmpValues = substr($sQuery, $iPos+10);
$iPos = strrpos($sTmpValues, ')');
$sTmpValues = substr($sTmpValues, 0, $iPos);
$iPos = strpos($sQuery, '(');
$sTmpColumns = substr($sQuery, $iPos+1);
$iPos = strpos($sTmpColumns, ') VALUES (');
$sTmpColumns = substr($sTmpColumns, 0, $iPos);
$aColumns = explode(', ', $sTmpColumns);
$aValues = explode(', ', $sTmpValues);
if (count($aColumns)>0 && count($aColumns) == count($aValues) && $iColumn < (count($aValues)+1)) {
$sNewQuery = "UPDATE ".$sTmpTable." SET";
$sTmpWhere = "";
$bNotFirst = false;
$iX = 0;
while ($iX<count($aColumns)) {
if ($iColumn == ($iX+1)) {
$sTmpWhere = " WHERE ". $aColumns[$iX]."=".$aValues[$iX];
$iX++;
continue;
}
if ($bNotFirst) {
$sNewQuery .= ",";
}
$sNewQuery .= " ".$aColumns[$iX]."=".$aValues[$iX];
$bNotFirst = true;
$iX++;
}
$sNewQuery .= $sTmpWhere;
}
return $sNewQuery;
}

PHP ~ Column count doesn't match value count at row 1

Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();

PHP insert multiple array into MySQL database

I have add/remove input box using jQuery for add video link and add into database like this:
<input name="video[]" class="" value="" />
<input name="video[]" class="" value="" />
I check and filter empty value than insert not empty value into my database like this:
$id = mysql_insert_id();
foreach(array_filter($_POST['video']) as $video_url) {
if (!empty($video_url)) {
$value['video_data'] = serialize((array(
array_filter($_POST['video'])
)));
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
}
}
Now, in database I see two row for id:
BUT, I need to insert one row for each id.
How do can I fix this ?
edit:
$id = mysql_insert_id();
Have you marked the id field in the database table as Auto Increment or not?
Because as per the current code, the $id is not updated anywhere. So it assumes the default value and inserts.
I would suggest to initialize $id before starting the foreach loop and then doing an increment after the SQL statement is executed
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
$i++;
You must create array values by php
$ar = new array();
$ar[]= null;
You submit form data multipart load
insert command by mysqldata
"Insert data into table db "
" for numbers all rows";
If you dont have auto increment of id, you can use
$id = "select max(id) from " .NEWS_FILES ; // execute sql and get maxid
than in your foreach add at a top $id++;

MySQL and PHP - insert NULL rather than empty string

I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng). Right now, if these values are not entered I pass along an empty string as a value. How do I pass an explicit NULL value to MySQL (if empty)?
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
This works just fine for me:
INSERT INTO table VALUES ('', NULLIF('$date',''))
(first '' increments id field)
If you don't pass values, you'll get nulls for defaults.
But you can just pass the word NULL without quotes.
All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db
Normally, you add regular values to mySQL, from PHP like this:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.
Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).
For some reason, radhoo's solution wouldn't work for me. When I used the following expression:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')? :("'".$val1."'")) . ", ".
(($val2=='')? :("'".$val2."'")) .
")";
The blank resulted in the correct null (unquoted) being inserted into the query.
your query can go as follows:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);
Check the variables before building the query, if they are empty, change them to the string NULL
you can do it for example with
UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'
2022 | PHP 7.3 | MySQL 5.7
Accepted answer by Rocket Hazmat gives me "NULL" as a string. So I change it to:
$intLat = !empty($intLat) ? "'$intLat'" : NULL;
$intLng = !empty($intLng) ? "'$intLng'" : NULL;

Categories