i have problem using active record, if i have active record like this
$data_array = array(
'Code Employee' => 'AC01',
'Status Employee' => 'Y'
);
$this->db->where($data_array);
$this->db->get('masteremp');
echo $this->db->last_query();
//Output query will be
SELECT * FROM masteremp WHERE `Code` `Employee` = 'AC01' AND `Status` `Employee` = 'Y'
i try edit DB_query_builder and i add this on line 2430
if(!empty($conditions)){
for($index = 0; $index < sizeof($conditions); $index++){
if (strpos($conditions[$index], '` `') !== false) {
$conditions[$index] = str_replace('` `', ' ', $conditions[$index]);
}
}
}
do u have method for field with space? i think my method is not efficiency.. thanks..
IN codeigniter you can escape values and identifiers.Try once like this..
Replace
$this->db->where($data_array);
With
$this->db->where($data_array,TRUE);//second parameter as TRUE
Then
//Output query will be
SELECT * FROM masteremp WHERE `Code Employee` = 'AC01' AND `Status Employee` = 'Y'
Related
I have a defined array. If is one from column (e.g. Bayern 'by') empty, then i do not receive variable $row_wohn_by and after in result get is: Notice: Undefined variable: row_wohn_by
Simply erase is not a solution for another operate. Expected is defined $row_wohn_by with 0 (zero) number.
Here is code:
$states = array(
'Baden-Württemberg' => 'bw',
'Bayern' => 'by',
'Berlin' => 'be',
'Thüringen' => 'th'
);
$numb_rows = mysqli_query($conn, 'SELECT COUNT(*)
FROM members
WHERE priv_staat = "Deutschland"
');
$numb_row = mysqli_fetch_array($numb_rows);
$total_wohn = $numb_row[0];
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
${'row_wohn_'.$states[$item_wohn['priv_land']]} = $item_wohn['count'];
${'row_wohn_per_'.$states[$item_wohn['priv_land']]} = number_format((($item_wohn['count'] / $total_wohn)*100), 2, ',', ' '); // calulate in %
}
$row_wohn_all = $total_wohn-($row_wohn_bw + $row_wohn_by + $row_wohn_be + $row_wohn_th);
$row_wohn_per_all = number_format((($row_wohn_all / $total_wohn)*100), 2, ',', ' '); // calulate in %
Thanks for help.
You wrote:
Expected is defined $row_wohn_by with 0
Looking at your query (SELECT priv_land, COUNT(*) AS count FROM members), this can only be the case when there are no rows with priv_land = 'by'. So within your while-loop just after your query, that variable never got set.
Solution: initialize all variables with value 0 and overwrite those with the results from your query:
foreach($states as $privLand) {
${'row_wohn_' . $privLand} = 0;
${'row_wohn_per_' . $privLand} = 0;
}
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
${'row_wohn_'.$states[$item_wohn['priv_land']]} = $item_wohn['count'];
${'row_wohn_per_'.$states[$item_wohn['priv_land']]} = number_format((($item_wohn['count'] / $total_wohn)*100), 2, ',', ' '); // calulate in %
}
For bonus points, rewriting everything to an array-notaition makes life a lot easier (example for only $row_wohn_*):
// Initialize all keys with value 0
$row_wohn = array_fill_keys($states, 0);
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
$row_wohn[ $states[$item_wohn['priv_land']] ] = $item_wohn['count'];
}
$row_wohn_all = $total_wohn - array_sum( $row_whon );
I have some query call and I want to replace it into one but I don't know it is possible. My database looks like:
My database calls:
$minbet = $mysql->query('SELECT `value` FROM `jackpot1_info` WHERE `name`="minbet"')->fetch_assoc();
$minbet = $minbet['value'];
$maxbet = $mysql->query('SELECT `value` FROM `jackpot1_info` WHERE `name`="maxbet"')->fetch_assoc();
$maxbet = $maxbet['value'];
$maxitems = $mysql->query('SELECT `value` FROM `jackpot1_info` WHERE `name`="maxitems"')->fetch_assoc();
$maxitems = $maxitems['value'];
$maxitemsinpot = $mysql->query('SELECT `value` FROM `jackpot1_info` WHERE `name`="maxitemsinpot"')->fetch_assoc();
$maxitemsinpot = $maxitemsinpot['value'];
It's simple, just select name and value in a single query and you will have each name and value pair in a separate row:
$select = $mysql->query('
SELECT `name`, `value`
FROM `jackpot1_info`
WHERE `name` IN ("minbet","maxbet","maxitemsinpot","maxitems")
');
while ($result = $mysql->fetch_assoc())
{
var_dump($result);
}
Output would look like:
array(2) {
'name' =>
string(12884901894) "minbet"
'value' =>
int(123)
}
array(2) {
'name' =>
string(12884901894) "maxbet"
'value' =>
int(456)
}
...
I'm sure you can do the rest.
Use IN instead of = for one query.
$select = $mysql->query('SELECT name,value FROM `jackpot1_info` WHERE `name` IN ("minbet","maxbet","maxitemsinpot","maxitems")');
$result = $mysql->fetch_assoc();
I have a table, with columns _photo(string) and f1(int)(this is users sex).
If _photo is empty I want to populate it with a string based on what column f1 contains.
I have this working fine for when a new user joins up, by doing this -
$sex = mysql_result(mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE `fk_user_id`='".$_SESSION[_LICENSE_KEY_]['user']['reg_id']."' "),0);
And then
if ($sex =='1') {
$no_photo = "no_photo_male.png";
}
if ($sex =='2') {
$no_photo = "no_photo_female.png";
}
if ($sex =='3') {
$no_photo = "no_photo_couple_ff.png";
}
if ($sex =='4') {
$no_photo = "no_photo_couple_mm.png";
}
if ($sex =='5') {
$no_photo = "no_photo_couple_mf.png";
}
$insertphoto= "UPDATE dsb_user_profiles SET _photo = '$no_photo' Where `fk_user_id` = '".$_SESSION[_LICENSE_KEY_]['user']['reg_id']. "' "; // note the use of reg_id and not user_id
if (!($res=#mysql_query($insertphoto))) {trigger_error(mysql_error(),E_USER_ERROR);}
I am trying to make a script that I can run on the database to update all the records to assign the correct string to all the records where _photo is empty.
I am new to mysql and php and can't work out how to cycle through each record and check f1, run the code to set the no_photo variable than insert it into the _photo column.
Any help is greatly appreciated!
Thanks.
You could loop trough records like this:
$userResult = mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE");
while($user = mysql_fetch_array($userResult)) {
if($user['f1'] == '1'){
$no_photo = "no_photo_male.png";
}
else if($user['f1'] == '2'){
//more else ifs
}
//your update query
}
Please try below update query:-
UPDATE Table_Name
SET _photo =
CASE
WHEN f1 = '1'
THEN "no_photo_male.png"
WHEN f1 = '2'
THEN "no_photo_female.png"
WHEN f1 = '3'
THEN "no_photo_couple_ff.png"
WHEN f1 = '4'
THEN "no_photo_couple_mm.png"
WHEN f1 = '5'
THEN "no_photo_couple_mf.png"
ELSE NULL
END
WHERE _photo = ''
You can update the database directly w/o PHP using nested MySQL IF() statements:
UPDATE user_profiles
SET _photo = IF(sex = 1, 'photo_1', IF(sex = 2, 'photo_2', IF(sex = 3, 'photo_3', IF(sex = 4, 'photo_4', NULL ) ) ) )
WHERE photo IS NULL;
I need to do a sql query in php for search some entries (so using WHERE). But the field used to search could be of variable number.
I have a page with a search form, with 4 Field. It sends via POST the fields to a search.php that make a query:
$gomme_sql = $data->query("SELECT * FROM table WHERE parameter1 = '$_POST['name1']' AND parameter2 = '$_POST['name2']' ORDER BY id ASC");
But I don't know which field are filled. So, if I don't enter anything in field1 from the search form, I shouldn't have parameter1 = '$_POST['name1']' in the WHERE query.
Have you any idea how to obtain this?
Thank you
You can check the post data before appending that clause to the query in a way like this:
edit: adding additional check:
$sql="select something from someTable ";
if(!empty($_POST['name1']) || !empty($_POST['name2'])) // add as many as you like
{
$sql.=" where ";
if(!empty($_POST['name1']))
{
$sql.="parameter1= $_POST['name1']";
}
// etc etc...
}
$sql.=" ORDER BY id ASC";
and so on.
Having said that, please, please use prepared statements with this sort of input from the user. This is SUPER open to sql injection. Please do read this: How can I prevent SQL injection in PHP?
You can write generic sql select function like this , if you need more complex SQL just modify it.
<?php
function sqlSelect($table, $sel, $wh = '', $groupby = '', $order = '', $add = '') {
$tb = $table;
if (is_array($table)) {
$tb = implode(',', $table);
}
if ($wh) {
if (is_array($wh)) {
$w = array();
foreach ($wh as $k => $v) {
$v = mysqli_real_escape_string($v);
if (is_null($v))
$w [] = "$k=null ";
else
$w [] = "$k ='$v'";
}
$wh = 'where ' . implode(' and ', $w);
}else {
$wh = "where $wh";
}
}
if ($groupby)
$groupby = "group by $groupby";
if ($order)
$order = "order by $order";
$sql = "select $sel from $tb $wh $groupby $order $add ";
return $sql;
}
//set _GET as this is console test
$_GET['name1']='Bob';
$where = array(
'name1'=>$_GET['name1']
);
echo sqlSelect('sometable' , '*' , $where) ."\n";
// select * from sometable where name1 ='Bob'
//or some complex stuff
echo sqlSelect('persons', "age,status" , array('name'=>'Maria' , 'likes'=>'PHP') , null, 'age' , 'limit 20');
//select age,status from persons where name ='Maria' and likes ='PHP' order by age limit 20
I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...