using variables to name a column in MySQLi table - mysqli

I am trying to create a table on the MySQLi server using input from user. This means some of the columns' names will be determined by the user input. These input can even be "" if the user does not want it. Hence nu of table columns will vary. I am finding it difficult to achieve this. My code is as follows:
<?php
$name = test_input($_POST["name"]);
$prj = test_input($_POST["project"]);
$recipe1 = test_input($_POST["recipe1"]);
$recipe2 = test_input($_POST["recipe2"]);
$recipe3 = test_input($_POST["recipe3"]);
$recipe4 = test_input($_POST["recipe4"]);
$tblname = test_input($_POST["prjtitle"]);
$tableExists = mysqli_query($conn, "DESCRIBE $tblname");
if (TRUE) {
$sql = "CREATE TABLE $tblname (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$name VARCHAR(15) NOT NULL,
$prj VARCHAR(15) NOT NULL,
$recipe1 VARCHAR(10) NOT NULL,
$recipe2 VARCHAR(10) NULL,
$recipe3 VARCHAR(10) NULL,
$recipe4 VARCHAR(10) NULL,
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table " .$tblname. " created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
Note that $recipe2, $recipe3, $recipe4 can have a value "" This means the user does not need the column & as such the column should not be create.
How can I correct above syntax?

You should check it one by one.
$userColumn = ($recipe1 == "" ? "" : $recipe1." VARCHAR(10) NOT NULL,");
$userColumn += ($recipe2 == "" ? "" : $recipe2." VARCHAR(10) NULL,");
$userColumn += ($recipe3 == "" ? "" : $recipe3." VARCHAR(10) NULL,");
$userColumn += ($recipe4 == "" ? "" : $recipe4." VARCHAR(10) NULL,");
then change if statement from
if (TRUE) {
$sql = "CREATE TABLE $tblname (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$name VARCHAR(15) NOT NULL,
$prj VARCHAR(15) NOT NULL,
$recipe1 VARCHAR(10) NOT NULL,
$recipe2 VARCHAR(10) NULL,
$recipe3 VARCHAR(10) NULL,
$recipe4 VARCHAR(10) NULL,
reg_date TIMESTAMP
)";
to
if (TRUE) {
$sql = "CREATE TABLE $tblname (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$name VARCHAR(15) NOT NULL,
$prj VARCHAR(15) NOT NULL,
$userColumn
reg_date TIMESTAMP
)";
Finally the code is below
<?php
$name = test_input($_POST["name"]);
$prj = test_input($_POST["project"]);
$recipe1 = test_input($_POST["recipe1"]);
$recipe2 = test_input($_POST["recipe2"]);
$recipe3 = test_input($_POST["recipe3"]);
$recipe4 = test_input($_POST["recipe4"]);
$tblname = test_input($_POST["prjtitle"]);
$userColumn = ($recipe1 == "" ? "" : $recipe1." VARCHAR(10) NOT NULL,");
$userColumn += ($recipe2 == "" ? "" : $recipe2." VARCHAR(10) NULL,");
$userColumn += ($recipe3 == "" ? "" : $recipe3." VARCHAR(10) NULL,");
$userColumn += ($recipe4 == "" ? "" : $recipe4." VARCHAR(10) NULL,");
$tableExists = mysqli_query($conn, "DESCRIBE $tblname");
if (TRUE) {
$sql = "CREATE TABLE $tblname (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$name VARCHAR(15) NOT NULL,
$prj VARCHAR(15) NOT NULL,
$userColumn
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table " .$tblname. " created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
See 'Conditional Operator' section in http://www.tutorialspoint.com/php/php_operator_types.htm for more information about ?: operator.

The code below works just fine. :
<?php
$name = test_input($_POST["name"]);
$prj = test_input($_POST["project"]);
$recipe1 = test_input($_POST["recipe1"]);
$recipe2 = test_input($_POST["recipe2"]);
$recipe3 = test_input($_POST["recipe3"]);
$recipe4 = test_input($_POST["recipe4"]);
$tblname = test_input($_POST["prjtitle"]);
$recipe2 = (empty($_POST["recipe2"])) ? "recipe2" :
test_input($_POST["recipe2"]);
$recipe3 = (empty($_POST["recipe3"])) ? "recipe3" :
test_input($_POST["recipe3"]);
$recipe4 = (empty($_POST["recipe4"])) ? "recipe4" :
test_input($_POST["recipe4"]);
$tableExists = mysqli_query($conn, "DESCRIBE $tblname");
if (TRUE) {
$sql = "CREATE TABLE $tblname (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$name VARCHAR(15) NOT NULL,
$prj VARCHAR(15) NOT NULL,
$recipe1 VARCHAR(15) NOT NULL,
$recipe2 VARCHAR(15) NOT NULL,
$recipe3 VARCHAR(15) NOT NULL,
$recipe4 VARCHAR(15) NOT NULL,
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table " .$tblname. " created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>

Related

not sure why I'm not getting the column? SqfliteDatabaseException (DatabaseException(no such column: test (code 1 SQLITE_ER[1]): flutter/dart

not sure why I'm not getting the column?
`await db.execute('''
CREATE TABLE user(
name TEXT,
surname TEXT,
email TEXT,
password TEXT
)
''');
Future<UserModel?> getLoginUser(name, String password) async {
assert(name != null);
var dbClient = await _database;
var res = await dbClient?.rawQuery("SELECT * FROM user WHERE "
"$name = '$name' AND "
"$password = '$password'");
if (res!.length > 0) {
return UserModel.fromMap(res.first);
}
return null;
}
`
SqfliteDatabaseException (DatabaseException(no such column: test (code 1 SQLITE_ERROR[1]): , while compiling: SELECT * FROM user WHERE test = 'test' AND 1234 = '1234') sql 'SELECT * FROM user WHERE test = 'test' AND 1234 = '1234'' args [])
the code I was using the user was $user but it gave me a error undifined name 'user'.
I tried several different ways but nothing worked.

set boolean value in sqlite android

I have column which is supposed to contain the true and false value in db. I understand that they should be in form of 0 and 1. I have an int column "status" but it always returns zero.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "( "
+ "ID INTEGER PRIMARY KEY ,"
+ VALUE + " TEXT NOT NULL, "
+ STATUS + " INTEGER NOT NULL)";
db.execSQL(create_table);
}
public int getStatus(String _id,int status)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + STATUS + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {_id});
if(cursor.moveToFirst()){
return cursor.getInt(cursor.getColumnIndex(STATUS));
} else {
return 0;
}
}
I need to set to true in the case below but item_status returns zero everytime. I checked the db and there is NULL in the whole status column.
if (success) {
status = 1;
int item_status = db.getStatus(fetchId(),status);
Toast.makeText(this, " item_status " + item_status , Toast.LENGTH_SHORT).show();
}

How to run sql query with bit field when using FromSql

I have this query:
return await this.DbContext.SearchRequestInfos.FromSql(
$#"{SqlStrings.SP.SearchSearchRequests}
#searchRequestId = {input.SearchRequestId},
#customerId = {input.CustomerId},
#customerName = {input.CustomerName},
#code = {input.Code},
#description = {input.Description},
#isGeneric = {input.IsGeneric},
#isActive = {input.IsActive}
"
).AsNoTracking().ToListAsync();
which creates this sql:
Executed DbCommand (69ms) [Parameters=[#p0='?' (Size = 4000), #p1='?', #p2='?', #p3='?', #p4='?', #p5='?', #p6='?' (DbType = Boolean), #p7='?' (DbType = Boolean)], CommandType='Text', CommandTimeout='30']
Portal> #p0
Portal> #searchRequestId = #p1,
Portal> #customerId = #p2,
Portal> #customerName = #p3,
Portal> #code = #p4,
Portal> #description = #p5,
Portal> #isGeneric = #p6,
Portal> #isActive = #p7
The issue is that #isGeneric and #isActive are bit fields, but the value is not getting used. In other words, the value should be true, which should be translated to 1, but it is not.
Is this a bug in EF Core, or am I doing something wrong?
The workaround is to add a property to convert the value to an int, and then the SQL works as expected.
public int? IsGenericBit { get {
if(this.IsGeneric.HasValue) return this.IsGeneric.Value ? 1 : 0;
return null;
} }
public int? IsActiveBit { get {
if (this.IsActive.HasValue) return this.IsActive.Value ? 1 : 0;
return null;
} }
Portal> Executed DbCommand (63ms) [Parameters=[#p0='?' (Size = 4000), #p1='?', #p2='?', #p3='?', #p4='?', #p5='?', #p6='?' (DbType = Int32), #p7='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
Portal> #p0
Portal> #searchRequestId = #p1,
Portal> #customerId = #p2,
Portal> #customerName = #p3,
Portal> #code = #p4,
Portal> #description = #p5,
Portal> #isGeneric = #p6,
Portal> #isActive = #p7
Note that that it specificies #6 and #7 as Int32 although they are actual bit in the database.
So the question is: Am I doing something wrong or is this a bug?

Web API 2 method developed using ADO.NET is not performing well, takes 53 seconds

I am creating API for Android app using Asp.Net Web API2. There is a method which fetches members data from the table. I am sorting and listing members based on arrangements(int) and name(string). The first sort by arrangements which value is not 0. then sort by name which value is 0. Everything working perfect but query execution taking 53234 ms as shown in postman.PErformance goes worst when I use EF6. I tested it using live URL and not on localhost. I have cloud server. Please check and help me in performance improvement. There are around 1000 rows/records only. There is an another query/stored procedure also which list nearby members based on latitude and longitude and execution time is hardly 2 seconds. Let me know if you need more information. Thanks
API Method
[HttpGet]
[ActionName("GetAllMembersOfClub")]
public APIResult GetAllMembersOfClub()
{
APIResult apiResult = new APIResult();
List<MemberData> lstMember = new List<MemberData>();
var cmd = new SqlCommand("Rotary1.usp_GetMembersWithArrangements", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#clubId", DbType.Int32).Value = clubID;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var objMember = new MemberData();
objMember.CountryCode = dr["CountryCode"].ToString();
objMember.ClubName = dr["ClubName"].ToString();
objMember.Name = dr["name"].ToString();
objMember.Classification = dr["Classification"].ToString();
objMember.OfficeAdrs1 = dr["OfficeAdrs1"].ToString();
objMember.OfficeAdrs2 = dr["OfficeAdrs2"].ToString();
objMember.OfficeAdrs3 = dr["OfficeAdrs3"].ToString();
objMember.ResAdrs1 = dr["ResAdrs1"].ToString();
objMember.ResAdrs2 = dr["ResAdrs2"].ToString();
objMember.ResAdrs3 = dr["ResAdrs3"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Phone = dr["Phone"].ToString();
objMember.Mobile = "+" + dr["CountryCode"].ToString() + dr["Mobile"].ToString();
objMember.EmailId = dr["EmailId"].ToString();
objMember.Since = dr["Since"].ToString();
objMember.Title1 = dr["title1"].ToString();
objMember.Title2 = dr["title2"].ToString();
objMember.Title3 = dr["title3"].ToString();
objMember.Title4 = dr["title4"].ToString();
objMember.PostHeld = dr["PostHeld"].ToString();
objMember.Imgg = dr["imgg"].ToString();
objMember.Anniversary = dr["Aniversary"].ToString();
objMember.Position = dr["Position"].ToString();
objMember.Ophone = dr["ophone"].ToString();
objMember.Children = dr["Children"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Latitude = dr["Latitude"].ToString();
objMember.Longitude = dr["Longitude"].ToString();
objMember.Mobile10 = dr["mobile10"].ToString();
objMember.Mobile2 = dr["mobile2"].ToString();
objMember.Mobile3 = dr["mobile3"].ToString();
objMember.Mobile4 = dr["mobile4"].ToString();
objMember.Mobile5 = dr["mobile5"].ToString();
objMember.Mobile6 = dr["mobile6"].ToString();
objMember.Mobile7 = dr["mobile7"].ToString();
objMember.Mobile8 = dr["mobile8"].ToString();
objMember.Mobile9 = dr["mobile9"].ToString();
objMember.Noti = dr["noti"].ToString();
objMember.Arrange = dr["arrange"].ToString();
try
{
objMember.DOB = Convert.ToDateTime(dr["DOB"].ToString()).ToString("dd-MM-yyy");
}
catch (Exception)
{
objMember.DOB = "";
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile2) || objMember.Mobile2 != "")
{
objMember.Mobile2 = "+" + dr["CountryCode"].ToString() + dr["mobile2"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile3) || objMember.Mobile3 != "")
{
objMember.Mobile3 = "+" + dr["CountryCode"].ToString() + dr["mobile3"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile4) || objMember.Mobile4 != "")
{
objMember.Mobile4 = "+" + dr["CountryCode"].ToString() + dr["mobile4"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile5) || objMember.Mobile5 != "")
{
objMember.Mobile5 = "+" + dr["CountryCode"].ToString() + dr["mobile5"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile6) || objMember.Mobile6 != "")
{
objMember.Mobile6 = "+" + dr["CountryCode"].ToString() + dr["mobile6"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile7) || objMember.Mobile7 != "")
{
objMember.Mobile7 = "+" + dr["CountryCode"].ToString() + dr["mobile7"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile8) || objMember.Mobile8 != "")
{
objMember.Mobile8 = "+" + dr["CountryCode"].ToString() + dr["mobile8"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile9) || objMember.Mobile9 != "")
{
objMember.Mobile9 = "+" + dr["CountryCode"].ToString() + dr["mobile9"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile10) || objMember.Mobile10 != "")
{
objMember.Mobile10 = "+" + dr["CountryCode"].ToString() + dr["mobile10"].ToString();
}
lstMember.Add(objMember);
}
dr.Close();
conn.Close();
cmd = new SqlCommand("Rotary1.usp_GetMembersWithArrangements1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#clubId", DbType.Int32).Value = clubID;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var objMember = new MemberData();
objMember.CountryCode = dr["CountryCode"].ToString();
objMember.ClubName = dr["ClubName"].ToString();
objMember.Name = dr["name"].ToString();
objMember.Classification = dr["Classification"].ToString();
objMember.OfficeAdrs1 = dr["OfficeAdrs1"].ToString();
objMember.OfficeAdrs2 = dr["OfficeAdrs2"].ToString();
objMember.OfficeAdrs3 = dr["OfficeAdrs3"].ToString();
objMember.ResAdrs1 = dr["ResAdrs1"].ToString();
objMember.ResAdrs2 = dr["ResAdrs2"].ToString();
objMember.ResAdrs3 = dr["ResAdrs3"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Phone = dr["Phone"].ToString();
objMember.Mobile = "+" + dr["CountryCode"].ToString() + dr["Mobile"].ToString();
objMember.EmailId = dr["EmailId"].ToString();
objMember.Since = dr["Since"].ToString();
objMember.Title1 = dr["title1"].ToString();
objMember.Title2 = dr["title2"].ToString();
objMember.Title3 = dr["title3"].ToString();
objMember.Title4 = dr["title4"].ToString();
objMember.PostHeld = dr["PostHeld"].ToString();
objMember.Imgg = dr["imgg"].ToString();
objMember.Anniversary = dr["Aniversary"].ToString();
objMember.Position = dr["Position"].ToString();
objMember.Ophone = dr["ophone"].ToString();
objMember.Children = dr["Children"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Latitude = dr["Latitude"].ToString();
objMember.Longitude = dr["Longitude"].ToString();
objMember.Mobile10 = dr["mobile10"].ToString();
objMember.Mobile2 = dr["mobile2"].ToString();
objMember.Mobile3 = dr["mobile3"].ToString();
objMember.Mobile4 = dr["mobile4"].ToString();
objMember.Mobile5 = dr["mobile5"].ToString();
objMember.Mobile6 = dr["mobile6"].ToString();
objMember.Mobile7 = dr["mobile7"].ToString();
objMember.Mobile8 = dr["mobile8"].ToString();
objMember.Mobile9 = dr["mobile9"].ToString();
objMember.Noti = dr["noti"].ToString();
objMember.Arrange = dr["arrange"].ToString();
try
{
objMember.DOB = Convert.ToDateTime(dr["DOB"].ToString()).ToString("dd-MM-yyy");
}
catch (Exception)
{
objMember.DOB = "";
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile2) || objMember.Mobile2 != "")
{
objMember.Mobile2 = "+" + dr["CountryCode"].ToString() + dr["mobile2"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile3) || objMember.Mobile3 != "")
{
objMember.Mobile3 = "+" + dr["CountryCode"].ToString() + dr["mobile3"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile4) || objMember.Mobile4 != "")
{
objMember.Mobile4 = "+" + dr["CountryCode"].ToString() + dr["mobile4"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile5) || objMember.Mobile5 != "")
{
objMember.Mobile5 = "+" + dr["CountryCode"].ToString() + dr["mobile5"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile6) || objMember.Mobile6 != "")
{
objMember.Mobile6 = "+" + dr["CountryCode"].ToString() + dr["mobile6"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile7) || objMember.Mobile7 != "")
{
objMember.Mobile7 = "+" + dr["CountryCode"].ToString() + dr["mobile7"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile8) || objMember.Mobile8 != "")
{
objMember.Mobile8 = "+" + dr["CountryCode"].ToString() + dr["mobile8"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile9) || objMember.Mobile9 != "")
{
objMember.Mobile9 = "+" + dr["CountryCode"].ToString() + dr["mobile9"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile10) || objMember.Mobile10 != "")
{
objMember.Mobile10 = "+" + dr["CountryCode"].ToString() + dr["mobile10"].ToString();
}
lstMember.Add(objMember);
}
dr.Close();
conn.Close();
apiResult.ReturnData = lstMember;
apiResult.ReturnCode = "1";
apiResult.ReturnMessage = "success";
return apiResult;
}
Queries/Stored Procedures
USE [myDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Rotary1].[usp_GetMembersWithArrangements]
#clubId INT
As
BEGIN
BEGIN
select * from main where arrange<>0 and club=#clubId order by arrange desc
END
END
GO
Second Procedure
USE [myDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Rotary1].[usp_GetMembersWithArrangements1]
#clubId INT
As
BEGIN
BEGIN
select * from main where arrange=0 and club=#clubId order by name
END
END
GO
Below is table schema
CREATE TABLE [dbo].[main](
[ID] [int] IDENTITY(1,1) NOT NULL,
[title1] [varchar](max) NULL,
[title2] [varchar](max) NULL,
[title3] [varchar](max) NULL,
[title4] [varchar](max) NULL,
[Name] [varchar](max) NULL,
[Classification] [varchar](max) NULL,
[position] [varchar](max) NULL,
[PostHeld] [varchar](max) NULL,
[OfficeAdrs1] [text] NULL,
[OfficeAdrs2] [text] NULL,
[OfficeAdrs3] [text] NULL,
[ophone] [varchar](max) NULL,
[Phone] [varchar](max) NULL,
[Mobile] [varchar](max) NULL,
[EmailId] [varchar](max) NULL,
[ResAdrs1] [text] NULL,
[ResAdrs2] [text] NULL,
[ResAdrs3] [text] NULL,
[Wife] [varchar](max) NULL,
[children] [varchar](max) NULL,
[DOB] [date] NULL,
[Since] [varchar](max) NULL,
[imgg] [text] NULL,
[Aniversary] [varchar](max) NULL,
[arrange] [int] NULL,
[club] [int] NULL,
[noti] [int] NULL,
[ClubName] [varchar](200) NULL,
[Latitude] [varchar](200) NULL,
[Longitude] [varchar](200) NULL,
[mobile2] [varchar](20) NULL,
[mobile3] [varchar](20) NULL,
[mobile4] [varchar](20) NULL,
[mobile5] [varchar](20) NULL,
[mobile6] [varchar](20) NULL,
[mobile7] [varchar](20) NULL,
[mobile8] [varchar](20) NULL,
[mobile9] [varchar](20) NULL,
[mobile10] [varchar](20) NULL,
[CountryCode] [varchar](10) NULL,
[Status] [int] NULL CONSTRAINT [DF_main_Status] DEFAULT ((1)),
CONSTRAINT [PK_main] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
public List<Member> GetMembers(string name="")
{
var param1 = new SqlParameter("#Name",name );
var result = _Context.Database.SqlQuery<Member>("exec GetMembersList #Name", param1).ToList();
return result;
}

CodeIgniter POST/GET default value

Can I set default value for POST/GET data if it's empty/false, something like
$this->input->post("varname", "value-if-falsy")
?
So I don't have to code like
$a = $this->input->post("varname") ?
$this->input->post("varname") :
"value-if-falsy"
Just found out not very long ago that I can also use ?:, eg.
$name = $this->input->post('name') ?: 'defaultvalue';
You have to override the default behavior.
In application/core create MY_Input.php
class MY_Input extends CI_Input
{
function post($index = NULL, $xss_clean = FALSE, $default_value = NULL)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
}
return $post;
}
$ret_val = $this->_fetch_from_array($_POST, $index, $xss_clean);
if(!$ret_val)
$ret_val = $default_value;
return $ret_val;
}
}
And then in your controller :
$this->input->post("varname", "", "value-if-falsy")
It works for me, I have used the #AdrienXL trick.
Just create your application/core/MY_Input.php file and call the parent method (you can find this methods inside CodeIgniter system folder system/core/Input.php:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class MY_Input extends CI_Input
{
function post($index = NULL, $default_value = NULL, $xss_clean = FALSE)
{
$value = parent::post($index, $xss_clean);
return ($value) ? $value : $default_value;
}
function get($index = NULL, $default_value = NULL, $xss_clean = FALSE)
{
$value = parent::get($index, $xss_clean);
return ($value) ? $value : $default_value;
}
}
So, when call the method, pass the default value:
$variable = $this->input->post("varname", "value-if-falsy");
You can simplify the code block as below
public function post($index = NULL, $xss_clean = NULL, $default_value = NULL )
{
if( is_null( $value = $this->_fetch_from_array($_POST, $index, $xss_clean ) ) ){
return $default_value;
}
return $value;
}
You can use this code before set_rules
empty($_POST['varname']) ? $_POST['varname'] = 'value if empty' : 0;