I cannot insert a word to mysql - php

if(isset($_POST['zodis'])) {
strpos($_POST['zodis'], ' ');
if($pos > 0) {
print '<h2> Only 1 word. </h2>';
} else {
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '"$_POST['zodis']"',CURRENT_TIMESTAMP);";
mysql_query($query) or die(mysql_error());
}
}
Where i made a mistake? Im new in PHP
it shows
Parse error: syntax error, unexpected T_VARIABLE in
C:\wamp\www\php_mysql.php on line 19

You forgot the ..
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";

$query = "INSERT INTO zodziai (id,zodis,date)VALUES (NULL, '".$_POST['zodis']."',".time().");";
your id field isn't autoincreament?
what kind of type field is your date field?

If you mix strings and variables, you should use "." to concatenate them:
...VALUES (NULL , '".$_POST['zodis']."',CURRENT_TIMESTAMP)...
(Note the point (.) before and after $_POST variable).
That is what I've seen taking a fast look, maybe there is something more.

You are not initializing $pos. Try this :
$pos = strpos($_POST['zodis'], ' ');
You have also forgotten the concatenation operator (.), in your query.
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";
Also avoid using mysql_ functions, PHP discourages using mysql_ functions and mysql_ functions will soon be deprecated, rather, use mysqli class or PDO.
Another suggestion, rather than sending CURRENT_TIMESTAMP in the query, create the table field using the following constraint
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and then pass NULL in the query, this will automatically set the date field in the corresponding row as CURRENT_TIMESTAMP.

Related

How do I store NULL date in Mysql [duplicate]

I am having trouble inserting null values into date fields into a MySQL table.
Here is the insert query:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.
The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.
Why can't I just insert null values into MySQL like this?
Try this:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
so for example if you put this into query:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
result should be:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
You should convert the null variable into a NULL string first
Like this:
if(is_null($date1)){
$date1 = 'NULL';
}
If you are using a MySQL date column, you must also specify that it should hold null when creating it, like this:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
It is also very important that you perform the query with bound parameters, for example using pdo
http://www.php.net/manual/en/pdo.construct.php
http://php.net/manual/en/pdo.prepared-statements.php
How do I insert NULL values using PDO?
Something like this:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));
If NULL does not work, just pass your date as "0000-00-00":
$chequeDate = "0000-00-00";
Backslash N is another way to express NULL in MySQL.
Try putting the value (backslash N): \N into one of the parameters like this:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Reference: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
In Derby, If you want to insert values except the ones you have declared Null (column_d1, column_d2), sql:
INSERT INTO DB.table (column_s1, column_s2) VALUES ('s1', 's2');
Probably answer is unneeded at this moment, but I found solution exactly I have been searching. Use an Expression to pass NULL like this:
['some_date_to_update' => new Expression('NULL')]
Hence, MySQL will understand what you want, and save (NULL) in DB instead of storing 0-dates. Hope this will help somebody.
In Mysql DATE data type Default NULL means
Some version set as 0000-00-00
Some version set as 1970-01-01
Years later, if someone is still experiencing this issue, you want to use PDO and bind the variables, everything will be taken care of no need to handle the null variables yourself.

Error while inserting data into Mysql database

I am trying to insert data into Mysql table, but it is giving me an error as-
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 'Scoretab VALUES ('UX 345','22','0.8562675')' at line 1
This is the php-mysql snippet that im using :
if($value >= 0.70){
$mu_id = $ros['c_id'];
$moc_id = $ram['t_id'];
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
$op1 = mysql_query($query) or die(mysql_error());
}
This is my table structure:
CREATE TABLE IF NOT EXISTS `Scoretab` (
`mu_id` varchar(10) NOT NULL,
`moc_id` int(5) NOT NULL,
`score` decimal(5,4) NOT NULL,
UNIQUE KEY `mu_id` (`mu_id`)
)
There could potentially be a few problems with this query
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
Does the number of columns match the fields your trying to insert? Have you tried using using specific column identifier Scoretab (col,col,col) values (val, val, val)
Does any of your values contain an unescaped apostrophe? You might want to consider using mysql_real_escape_string for $mu_id and intval for $moc_id maybe!
$value is a float you don't need to ad apostrophes while inserting
Are you sure you are connected to the same database you have this table in?
this could be a possible working solution (edit)
if ($value >= 0.70)
{
$mu_id = mysql_real_escape_string($ros['c_id']);
$moc_id = intval($ram['t_id']);
$query = "INSERT INTO `Scoretab` VALUES ('$mu_id', $moc_id, $value)";
$op1 = mysql_query($query) or die(mysql_error());
}
try this
$query="INSERT INTO Scoretab (mu_id,moc_id,score) VALUES ('$mu_id','$moc_id','$value')";
The error seems to be before the table name Scoretab. Did you check your syntax carefully?
Sometimes we don't see what's right in front of our eyes! :D
Just replicated the example and everything worked for me.

Create mysql table from PHP array

A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.
I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.
$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';
while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());
**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.
For one, this
'CREATE TABLE $table'
will NOT fill in $table, but will be LITERALLY
CREATE TABLE $table
use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql. There might be more, but probably easily discoverable trough mentioned debugging...
You apparenty have an extra trailing comma:
CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
col1 INT,
col2 INT,
-- ^ here
)
1
change the single quotes (') to double quotes (") for your query.
2
or use dot operator (.) to append php variable.
$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';
// Output
SELECT * FROM mytable
SELECT * FROM $tableName
You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.
If you are trying to get rid of the trailing slash you can also do this by using a counter.
$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
$query .=" ".$listing[0];
if ( $key+1 != $fieldsCount )
{
$query .=',';
}
}

How to get just inserted row from MySql to a php variable?

I'm using Zend Framework and MySql to create my web-application. My SQL-code is the following at the moment:
public static function newTestResult($testId, $accountId, $score, $deviation, $averageTime)
{
try
{
$db = self::conn();
$statement = "INSERT INTO test_results(test_id, test_person_id, score, standard_deviation, average_answer_time, created_at)
VALUES(" . $testId . ", " . $accountId . ", " . $score . ", " . $deviation . ", " . $averageTime . ", NOW())";
$db->query($statement);
$db->closeConnection();
}
catch(Zend_Db_Exception $e)
{
error_log($e->getMessage());
}
}
Now what I'm asking is: How can I get the just inserted row to a variable in PHP? I would want to get my hands on the id-value what MySql is creating automatically for the row.
Here is my table code:
CREATE TABLE test_results(
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_id int UNSIGNED NOT NULL,
test_person_id int UNSIGNED NOT NULL,
score float UNSIGNED NOT NULL,
standard_deviation float UNSIGNED NOT NULL,
average_answer_time float UNSIGNED NOT NULL,
removed boolean NOT NULL DEFAULT 0,
created_at datetime) CHARACTER SET utf8 COLLATE utf8_general_ci;
Take a look at the MySQL function "LAST_INSERT_ID()"
See also this forum for more detail on the methods available.
http://forums.phpfreaks.com/topic/188084-get-last-mysql-id-using-zend-frameworks/
In "plain" PHP, I usually use the mysql_ functions. The mysql_insert_id() function returns the key of the last row inserted. I'm not advocating this over using the Zend way, just giving context:
mysql_query("INSERT INTO ... query");
$id = mysql_insert_id();
Then reference that ID in writing other queries related to that inserted row.
This should give you the last insert id from the last query made.
$db->lastInsertId()
try this:
$query="SELECT id FROM test_results WHERE test_id=$testId";
$id=$db->query($query);
I assume this is what you're looking for, otherwise you can change the WHERE condition to whatever you need.
From the MySQL manual: "If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function." This refers to the C function.
In the PHP manual, you are suggested to use the PDO function instead. http://php.net/manual/en/function.mysql-insert-id.php PDO::lastInsertId
And apparently, "The insert() method on Zend_Db_Table will return the value of the last insert id." http://osdir.com/ml/php.zend.framework.db/2007-04/msg00055.html
To get last two records from any table you can use the following query
SELECT * FROM aa WHERE ID IN(
(SELECT COUNT(*) FROM aa),
(SELECT COUNT(*) FROM aa)-1
)

trying to INSERT NULL if input field left blank

I'm trying to insert NULL into the mySQL databse with PHP.
I've got:
$myVariable=$_POST[inputfield];
if(!is_numeric($myVariable) || $myVariable==0){
$myVariable=NULL;
}
My database field is decimal, and IS NULL has been set. It keeps reverting to 0.00 if input is left blank. How do I set NULL if left blank, so I can call a php if NULL function?
Edit Calling if NULL in decimal is not correct?
<? if ($debit==NULL || $debit=="0.00") {echo 'Awaiting Cost';}
elseif ($debit != NULL || $debit!="0.00") { echo "£$debit";}?>
This displays my message correctly, so if if NULL is useless for a decimal i'll just leave 0.00. Is this hacky?
SQL structure for those who asked:
`myTableField` decimal(10,2) default NULL,
If you are composing an SQL statement by appending the value of the $myVariable variable, then you should look if it's NULL or not and modify the SQL statement accordingly.
For example, if your code is something like:
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
then you should change it to something like:
if (is_null($myVariable)) {
$sql .= "myVariable = NULL";
} else {
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
}
Try it on the SQL side:
$sql = "INSERT INTO `table` (`field1`) VALUES (IF($myVariable == 0, NULL, $myVariable))";
try:
$myVariable="NULL";
.
if your code is:
$val=NULL;
mysql_query("SET #v=$val");
the MySQL got the string:
SET #v=0;
it's like using :
echo "SET #v=$val";
you can filter field's data in MySQL itself, using a TRIGGER:
CREATE TRIGGER table1_update BEFORE UPDATE ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);
CREATE TRIGGER table1_create BEFORE INSERT ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);

Categories