I cannot get default in sql to work - php

I am having an issue with sql right now; I have gave a value a default so if the field is left empty when the user submit, but it is not working. When the user submits an empty field to leave a comment instead of it default to anon it does nothing. Also, in the datebase the field is empty.
name VARCHAR (50) default 'anon',
$name= $_POST['name'];
$title= sha1($_POST['title']);
$texts= $_POST['texts'];
$forum_id = $_POST['forum_id'];
$name = str_replace("'","''",$name);
$title = str_replace("'","''",$title);
$title = str_replace("b074acd521","STREAMER",$title);
$texts = str_replace("'","''",$texts);
$title = substr($title,0,8);
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
mysqli_query($conn1, $sql) or die('Error inserting to database.');
mysqli_close($conn1);
header('Location: requests.php');
Is there another way to do it or am I just doing something wrong?

The SQL query your using will not insert the default value from your database because you are specifying a value for name (even if that value is an empty string, or null) :
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
Instead if you want the default value to be inserted into the name field you must not specify the name column in the insert statement :
$sql = "INSERT INTO post (title, texts, forum_id) VALUES ('$title', '$texts', '$forum_id')";
In SQL query you can specify for which fields, values will be provided in the query and remaining fields from the table would contain default value (in case of AUTO_INCREMENT, the next integer value will be used).

Where you given the default value directly applied in SQL? the value left in DB ultimately is what exactly you passed to DB server by SQL way, or just you defined a variable where if it don't accept a value from user then use the default value instead, please try to debug this to insure the value was handled correctly.

while insert the values you shouldn't give the column which you set default value
below Example explain it...Try like this...
create table er(id int,name char(10),gender char(2)default 'M')
Here i took gender as default
now i insert the values
insert into er (id,name)values(1,'poda')
select * from er

Related

Dynamic SQL Inserts for JSON data [PHP]

Near daily I am tasked with inserting JSON data into a relational database via PHP, as is with JSON data some records with have certain columns while others do not, and this tends to be a problem when inserting into a table.
If I am inserting several thousands students a record might look like
{"name": "Billy Jackson", "Height": 172, "DOB" : "2002-08-21"}
However its not certain that height and or DOB is set in any record, what I currently do is something like
<?php
foreach($records as $json){
$name = addslashes($json['name']);
if(isset($json['Height']){
$height = $json['Height'];
}
else{
$height = "NULL"
}
if(isset($json['DOB']){
$dob = $json['DOB'];
}
else{
$dob = "NULL"
}
}
$db->query("INSERT INTO table (name, height, dob) VALUES ('$name', $height, '$dob')");
As you may see this is not elegant nor does it work for several types, fields like DOB do not accept NULL, nor do enums.
Is there a more elegant built in solution, to only try and insert into columns where the value exists in the JSON.
Is this something prepared statements handle?
EDIT
lets say the example record above did not have DOB setthe insert statement would look like
"INSERT INTO table (name, height, dob) VALUES ('Billy Jackson', 172, 'NULL')"
Which fails, if have $dob be set to null ($dob = null) if it is not set then the insert statement looks like
"INSERT INTO table (name, height, dob) VALUES ('Billy Jackson', 172, '')"
Which fails
Why even include the dob column? because some records do have a dob and I want them included in the insert
Empty string '' is not the same as null. Nor is the string "null". Since your query explicitly quotes the contents of the $dob variable, you're quoting the string null such that it becomes "null" which is definitely not null. :)
To avoid the need to mess with quotes (and SQL injection), you'll want to use a prepared statement, something like this:
$db->prepare('INSERT INTO table (name, height, dob) VALUES (?, ?, ?)');
Then when you bind the values, PHP will automatically take care of what fields need quotes and which don't.
Also note, you can shortcut this:
if (isset($json['Height']){
$height = $json['Height'];
} else {
$height = "NULL"
}
Into just this:
$height = $json['Height'] ?? null;
Which would eliminate a bunch of your code and make your bind something like this:
$stmt->bind_param(
'sis',
$json['name'],
$json['Height'] ?? null,
$json['dob'] ?? null
);
You should start with addressing the problems in your table design.
All columns that MUST have data should be set to NOT NULL, and a default value set, if appropriate. It may not be appropriate to have a default value for User Name, for example, so don't set one.
All columns that MIGHT have data should be set to accept NULL, with a default value set as appropriate. If there's no data then the correct value should generally be NULL and that should be set as a default.
Note that both DATE and ENUM columns can accept NULL if properly configured.
Once you have your column definitions correct you can generate an INSERT query based on the actual values you find in your JSON file. The data integrity rules you set in your table definition will ensure that appropriate values are entered for any row that is created with values missing, or that the row is not created if 'must have' data is missing.
This leads to some code like this, based on PDO prepared statements:
$json = '{"name": "Billy Jackson", "Height": 172, "DOB" : "2002-08-21"}';
$columnList = [];
$valueList = [];
$j = json_decode($json);
foreach($j as $key=>$value) {
$columnList[] = $key;
// interim processing, like date conversion here:
// e.g if $key == 'DOB' then $value = reformatDate($value);
$valueList[] = $value;
}
// Now create the INSERT statement
// The column list is created from the keys in the JSON record
// An array of values is assembled from the values in the JSON record
// This is used to create an INSERT query that matches the data you actually have
$query = "INSERT someTable (".join(',',$columnList).") values (".trim(str_repeat('?,',count($valueList)),',').")";
// echo for demo purposes
echo $query; // INSERT someTable (name,Height,DOB) values (?,?,?)
// Now prepare the query
$stmt = $db->prepare($query);
// Execute the query using the array of values assembled above.
$stmt->execute($valueList);
Note: You many need to extend this to handle mapping from JSON keys to column names, format changes in date fields, etc.

PHP set a default value for database insert

I have a number box <input type='number' step='any' name='number' id='number'>
and I take that value and call it in a function like so:
insertIntoDB($number)
function insertIntoDB($number = null){
//insert into db
"INSERT INTO 'tablename' (number) VALUES " . $number;
}
and 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 ' '
Is there away so if the user leaves the field blank it will enter the value as null?
You can set default values when creating the table itself, but apart from that, the code you pasted is missing some brackets:
INSERT INTO `tablename` (number) VALUES (" . $number.")";
If you want to use a NULL when inserting and get a default value in the table, you can do it when creating the table like this:
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
someField VARCHAR(15) NOT NULL DEFAULT 'on'
)
Now when you try to insert data into it, you can do the following:
insert into `tablename` (id, someField) values (null, null)
and get a row with an incremented ID and the string 'on' in the column someField.
If you want to check for nulls when inserting data into a table, you can then use something like the following to ensure you have the value:
$someField=(isset($number))?$number:'null';
INSERT INTO `tablename` (number) VALUES (" . $someField.")";
This is assuming you have already verified that $number is either numeric or isn't submitted when sending the form.

php adding wrong value to mySql database

i have built an air for android app that posts content to facebook and on success sends a url query to a php file to add the post id of the content along with fb_id and the users name. the problem is it is not adding the value i am giving it it is instead adding the same number(dont know where it is coming from) to the post_id and fb_id. i know the right values are being sent by the mobile app.
php:
<?php
/*
------------variables set in flash--------------
videoVars.postId = result.id
videoVars.uid = uid //fb user id
videoVars.firstName = firstName
videoVars.lastName = lastName
*/
$postId = $_REQUEST['postId'];
$uid = $_REQUEST['uid'];
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
echo $postId.'<br/>';
echo $uid.'<br/>';
echo $firstName.'<br/>';
echo $lastName.'<br/>';
//connect to database
include('db-connect.php');
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
?>
the value i am getting for post_id and user_id are the same even though they should be different. i manually typed the vars in to addressbar in browser and it still misbehaved in the same way. the only way i can add more than one row is to add it in the sql tab of phpMyAdmin
If your echo calls output the correct values, check your database table structure and make sure there's no UNIQUE key set for fb_id.
Then, make sure you're escaping all your content with mysqli_real_escape_string ( mysqli $link , string $escapestr ). http://ca3.php.net/manual/en/mysqli.real-escape-string.php
Is content_id an auto_increment value? If so, try passing NULL for it, without the single quotes, instead of an empty string.
To debug, you can also try echoing your query (first assign it to a variable $sql = "[QUERY HERE]";, then pass the variable to the function, then echo the $sql variable and finally call your file manually.
I guess that you have problem on content_id field. it should has auto_increment property.
In your sql, when you inserts content_id as a blank value '' it will convert to 0, next time when you insert a blank value again you will has "Duplicate entry '0' for key 'PRIMARY'" message.
to fix it just remove the primary key field in your query
i.e:
$addVideo = mysqli_query($dbc , "INSERT INTO content ( post_id, fb_id, first_name, last_name ) VALUES('".$postId."','".$uid."','".$firstName."','".$lastName."')");
Or you can insert a null value for it:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES(null,'".$postId."','".$uid."','".$firstName."','".$lastName."')");
You can try to print out your current - wrong sql error like this:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
if (!$addVideo) {
printf("Error: %s\n", mysqli_error($dbc));
}
The problem is the id were being stored as ints in the database and the biggest allowable int value is 2147483647 which is being put in each time and as the numeric ids are bigger numbers than 2147483647 and one of the fields is set to unique it can only add one row. i have changed the type to bigint and it is working fine now. i have also implemented some of # dAngelov suggestions.

Sql Error - Incorrect integer value

I'm getting following error when I submit a form:
Can't added a new post. Incorrect integer value: '' for column 'aid' at row 1
Php Code:
$insert = mysql_query("INSERT INTO brt_articles VALUES( '', '$post_title', '$des',
'$date', '$org_date')");
if($insert)
{
echo "<font color=green>Successfully added a new article.</font>";
header("Refresh:3; url=allbrtarticle.php");
}
else
{
echo "<font color=red>Can't added a new post</font>" .
mysql_error();
}
In my Localhost It's ok. But in server why it's giving me a error message ?
Probably that DB has differents settings than your local. STRICT_TRANS_TABLES mode might be turned on.
Try SELECT ##GLOBAL.sql_mode; and SELECT ##SESSION.sql_mode;.
The aid field does not accept '' value as input.
The safest way is to specify column names as you are sending the query.
INSERT INTO brt_articles (title_field, description_field, date_field, org_date, fieldname) VALUES('$post_title', '$des', '$date', '$org_date');
If aid is a primary key, simply omit that field in your query
INSERT INTO brt_articles VALUES('$post_title', '$des', '$date', '$org_date')
aid is a column that is an integer, and you're trying to insert '' into it. '' is not a number, so the insertion fails.
Perhaps there's a server setting to auto-convert the incorrect type, but you shouldn't rely on it (as you've just found out)
This causes the error aid(INT) - which is included on you table columns(first column).
If its auto increment remove the ''.
$insert = mysql_query("INSERT INTO brt_articles VALUES('$post_title', '$des',
'$date', '$org_date')");
Regards
try
"INSERT INTO brt_articles VALUES('".$post_title."', '".$des."', '".$date."', '".$org_date."')"
Remove first '' it's not needed as MySQL automatically add it if its primary key and auto_increment.
your local db has the value of that column set to auto increment or has a default value.
on the server db, the table definition is not the same.
review and compare the table definitions and then make them consistent.

Insert new row in a table and auto id number

I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?
Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.
The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()
The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.
Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)
You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php

Categories