MySQL ERROR: Column 'Time' cannot be null - php

I get the error: Column 'Time' cannot be null when using the query below, it works fine the first time when there is no duplicate but then when trying to update again I get the error: Column 'Time' cannot be null
mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time=Time+INTERVAL $time SECOND
Videos=Videos+'$videos',
Credits=Credits+'$credits'
",
$conn
);
Hope you can spot my error as I am new to this, thanks!
Here is some more of my code:
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
// Protect against sql injections
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Insert
$retval = mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(Time,now()),INTERVAL '$time' SECOND),
Videos = Videos+'$videos',
Credits = Credits+'$credits'
",
$conn
);
// End Query
if($retval) {
echo "Success! Updated $user with Time: $time - Videos: $videos - Credits: $credits";
} else {
echo "<b>ERROR:</b><br>" . mysql_error();
}
mysql_close($conn);

It should be:
mysql_query("
INSERT INTO
$table(Username, `Time`, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(`Time`,now()),INTERVAL '$time' SECOND)
,Videos = Videos+'$videos'
,Credits = Credits+'$credits'
",
$conn
);
Don't forget to put single quotes around all injected variables, otherwise mysql_real_escape_string will not protect you.
See:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

If there's no duplicate, then this query will do an insert, and the Time value will be null, as no value was ever set. Null + anything is null, hence the error.
Try ... Time = COALESCE(Time, 0) + INTERVAL $time SECOND or similar to get aroun dit.

Related

Sending Form Data to MySQL

I'm trying to send form data to MySQL. I've found tonnes of code on the net, so I'm copying, and pasting and creating PHP scripts and adding them to my phpAdmin, but I really have no idea.
I don't know what to add to my form as an action to tell the form to send the data to my database. I already have an action code in the form, am I able to have two?
I have created a table in my phpAdmin, but I don't know if it actually will work.
This is my PHP code that I have stuck in my public_html folder, with generic username, database name, and password. I use an IP address instead of Localhost, as this database is on the Internet through Bluehost rather than my own computer.
<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$submission_id = $_POST['submission_id'];
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$homeclub = $_POST['homeclub'] ;
$course1 = $_POST['course1'] ;
$course2 = $_POST['course2'] ;
$winner = $_POST['winner'] ;
$db_host = 'localhost';
$db_username = 'userrname';
$db_password = '';
$db_name = 'dbName';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM `table_name` WHERE `submission_id` = '$submission_id'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `table_name` SET
`name` = '$name',
`email` = '$email',
`homeclub` = '$homeclub',
`course1` = '$course1',
`course2` = '$course2'
`winner` = '$winner'
WHERE `submission_id` = '$submission_id'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `table_name` (submission_id, formID, IP,
name, email, homeclub, course1, course2, winner)
VALUES ('$submission_id', '$formID', '$ip',
'$name', '$email', '$homeclub', '$course1', '$course2', '$winner') ")
or die( mysql_error());
}
?>
Any assistance will be greatly appreciated.
I'm sorry but your code is very outdated. You need to validate your value in case something is missing. I used Nulls coaling to do this (-> ?? ""), then you use mysql. You could use mysqli but I prefer and recommend PDO because it's easier. And instead to ask database if there is an insert first, just say hey update if there is an insert with the same id, or insert is (that makes Replace). But in order to do this, make submission_id unique in database
https://joshuaotwell.com/use-mysql-unique-constraint-in-phpmyadmin/
PS: this code is not tested but it should work, otherwise send me your full error report message
<?php
// read variables or assign them a default value
$submission_id = $_POST['submission_id'] ?? 0;
$name = $_POST['name'] ?? "";
$email = $_POST['email'] ?? "";
$homeclub = $_POST['homeclub'] ?? "";
$course1 = $_POST['course1'] ?? ""; // make array out of this
$course2 = $_POST['course2'] ?? "";
$winner = $_POST['winner'] ?? "";
// mysql is deprecated use pdo instead
$pdo = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_username, $db_password)
// if exists -> replace, if not exist insert (replace makes that in one query)
// submission_id must be flagged as unique in mysql otherwise it will insert a new row every time
// I use prepared statements so first tell database what to do then the value
// prevents hacking and increase secureity
$query = 'REPLACE table_name SET
name = :name
, email = :email
, homeclub = :homeclub
, course1 = :course1
, course2 = :course2
, winner = :winner
, submission_id = :submission_id';
$statement = $pdo->prepare($query);
$statement->execute(array(
':name' = $name
, ':email' = $email
, ':homeclub' = $homeclub
, ':course1' = $course1
, ':course2' = $course2
, ':winner' = $winner
, ':submission_id' = $submission_id
));

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;
}

SQL Error 1064 Not sure

I am trying a new way of inserting data into a SQL. I am getting this error
insert into tracking_clients set / agreement_type = 'Purchase' , existing_client = 'Yes' ,
sales_rep = '1'
Array ( [agreement_type] => Purchase [existing_client] => Yes [sales_rep] => 1
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 '/ agreement_type = 'Purchase' ,
existing_client = 'Yes' , sales_rep = ' at line 2mysql err no : 1064
I use a form with action POST
In my submit page I use the following
//Drawn from Form Information used to Update Database
$sub1 = $_REQUEST['agreement_type'];
$sub2 = $_REQUEST['existing_client'];
$sub3 = $_REQUEST['sales_rep'];
update_lbs($sub1, $sub2, $sub3, $sub4,....); //Not full string posted here
function update_lbs($sub1, $sub2, $sub3, $sub4,.....)
{
global $host;
global $username;
global $password;
global $db_name;
//Insert if dates is required
date_default_timezone_set('Africa/Johannesburg'); //Global Time one for South Africa
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d") ;
$time = date("H:i:s");
$insertSuccessful = false;
$new_msisdn = '0' . substr($msisdn, 2); //Not Sure If this is required in normal SET command
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name))
//First Database Insert change table name as required
$sql = "insert into tracking_clients set
agreement_type = '".$sub1."' ,
existing_client = '".$sub2."' ,
sales_rep = '".$sub3."',
sub_date = '".$date."'" //Last of the code for SET
;
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
I am not sure what would be causing this error at all. I know this question is a common one but reading thru the other awnsers I am not getting the error
you have a tab characters beetween "set" and "agreement_type"
I am assuming you are using mysql here. The insert statement doesn't use set it simply inserts the values.
Something like this:
insert into yourTable (val1, val2, val3)
or
insert into yourTable (col1, col2, col3) values (val1, val2, val3)
not
insert into yourTable set col1=val1 etc...

php mysql query not executing correctly

I have a weird problem with my sql script.
I have a string
$query = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message)
VALUES ('93361357', '2162', '27761144734', 'Hoekom');";
But when I execute that string it inserts it to the table but eventid stays 0, if I run that exact command in cmd it works perfectly?
Any ideas why this is not inserting all the values?
Edit Full code
<?php session_start();
$link = mysql_connect("localhost", "username", "password"); //removed u and p for posting
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db("db", $link) //removed db name for posting
or die ("Couldn't open smss:" . mysql_error());
$id = $_SESSION['id'];
$message = $_REQUEST['promo_message'];
$timeToSend = $_REQUEST['timeToSend'];
$dateToSend = $_REQUEST['dateToSend'];
if(isset($_REQUEST['input_cell']))
{
$receiver = $_REQUEST['input_cell'];
if($receiver != '')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
mysql_query($query1);
echo mysql_error();
}
}
if(isset($_REQUEST['single_cell']))
{
$receiver = $_REQUEST['single_cell'];
if($receiver != 'none')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$query2 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query2);
echo mysql_error();
}
}
if(isset($_REQUEST['sento_group']))
{
$array = $_REQUEST['sento_group'];
foreach($array as $receiver)
{
if($receiver != 'none')
{
$query = 'SELECT cell_number FROM cell_groups WHERE group_id ="'.$receiver.'"';
$result2 = mysql_query($query) or die('Fail');
while($row=mysql_fetch_array($result2))
{
$response_string = sendSMSPortalSchedule($message, $row['cell_number'], $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$to = $row['cell_number'];
$query3 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$to', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query3);
echo mysql_error();
}
}
}
}
}
This is the table
id = INT
eventid = BIGINT(20)
bus_id = INT
cell_num = VARCHAR
sms_message = VARCHAR
The SQL command itself is correct. The problem must be elsewhere.
Firstly, are you sure that the values of your parameters are correct? Try outputting the query after variable interpolation to see if it is correct:
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message')";
echo $query1;
Seondly I notice that in you have INSERTs in multiple places. Make sure all of them work as expected. Remember that the one you think is executing may be different from the one that is actually executing.
I found the problem, the service I was using got changed to return XML where it usually just returned an integer, this caused me to try and insert XML into my BIGINT field, which is not possible. So in the end the problem was caused by an updated service that didn't notify clients about changes.

MySQL UPDATE Resetting values randomly?

I have a highscores table, it seems to be working fine apart from the problem of at random times it seems to be resetting certain users back to 0, this is my query:
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Main Query
$retval = mysql_query("
INSERT INTO
highscores(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = '$credits'
",
$conn
);
It updates fine most of the time, can anyone see what the problem is?
I guess you want to update the credit and not zero it.
Say you set $credit to 0 before you execute the query, than the ON DUPLICATE KEY UPDATE part will cause the current user credits to be zeroed. Instead you should do something like this:
<?php
$user = 109;
$time = time();
$videos = 'something';
$credits = 0;
$retval = mysql_query("INSERT INTO
highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = Credits + 1", $conn);
I think you are looking for
$query = sprintf("INSERT INTO highscores(Username, Time, Videos, Credits)
VALUES('%s', '%s', '%s', '%s')
ON DUPLICATE KEY UPDATE Time = Time + %2$s, Videos = Videos + %3$s, Credits = Credits + %4$s"
mysql_real_escape_string($user), // escape every variable you will be using in
mysql_real_escape_string($time), // an SQL query to protect yourself against
mysql_real_escape_string($videos), // SQL injection or use parametriezed
mysql_real_escape_string($credits)); // queries with wrappers such as PDO or MySQLi
$retval = mysql_query($query,$conn);
If a user exists already, this will just add to the current Credits the new value, but it won't change anything else. This seems logical to me. If you also need to increment other columns such as Videos, do the same thing I did for the Credits.
Other have pointed what causes this behaviour. Here's an alternative syntax for the ON DUPLICATE UPDATE
// Main Query
$retval = mysql_query("
INSERT INTO highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = Time + VALUES(Time),
Videos = Videos + VALUES(Videos),
Credits = Credits + VALUES(Credits)
",
$conn
);

Categories