I try to update my table using join in Codeigniter but I get error
Unknown column 'filter.ID_AREA' in 'where clause
$this->db->join('filter', 'filter.ID_AREA = area.ID_AREA', 'left');
$this->db->set('ID_VERIFIKASI', '3');
$this->db->where('pelayanan.ID_AREA', $ID_AREA);
$this->db->where('filter.ID_AREA', $ID_AREA);
$this->db->where('filter.ID_RAYON', $ID_RAYON);
$this->db->where('pelayanan.ID_RAYON = filter.F1_RAYON');
$this->db->where('SUBSTR(TGLRUBAH, 3, 6) = filter.F1_BULANTAHUN');
$this->db->where('ID_VERIFIKASI', '2');
$this->db->where('ID_KENDALA is not null');
$this->db->update('pelayanan');
if ($this->db->affected_rows() > 0) {
return true;
}
else {
return false;
}
How can I update table using join in Codeigniter?
I would recommend that you avoid UPDATE JOIN using the Query Builder. Use an SQL string and query it instead.
From what I see in your snippet you may try to convert it to something like this :
public function updateMyDB() {
$sql =
"UPDATE pelayanan P " .
"LEFT JOIN filter F ON F.ID_AREA = area.ID_AREA " .
"SET ID_VERIFIKASI = 3 "
"WHERE P.ID_AREA = " . $ID_AREA .
"AND F.ID_AREA = " . $ID_AREA .
"AND F.ID_RAYON = " . $ID_RAYON .
"AND P.ID_RAYON = F.F1_RAYON " .
"AND SUBSTR(TGLRUBAH, 3, 6) = F.F1_BULANTAHUN " .
"AND ID_VERIFIKASI = 2 " .
"AND ID_KENDALA IS NOT NULL";
$this->db->query($sql);
return ($this->db->affected_rows() > 0);
}
This is a not a perfect query, there is no reference to table "area" and to ID_VERIFIKASI and ID_KENDALA. I didn't test the query but I'm pretty sure it will fail in the JOIN, but you got the idea. Up to you to create the correct sql for your needs :)
Hope it helps!
You can try this approach:
function edit_save($data, $post_id, $user_id)
{
$this->db->set($data)
$this->db->where('table1.user_id', $user_id);
$this->db->where('table1.post_id', $post_id);
$this->db->where('table1.data_id_fk = table2.data_id');
$this->db->update('table1, table2');
}
Related
I'm trying to run multiple queries on a MySQL server at the same time from PHP with the same database connection. I have run the SQL statement on the server itself but the response is as expected. I'm getting no SQL exceptions but just no SQL query response at all (the result is FALSE).
Is this because you can't query when another query is already active on the same connection?
The code loads data from the database table with people's names and last paid date information. This is displayed in a form and then the user can select members to update payments for. Then, the part I'm stuck on is the second query where the selected names are trying to find family_id for families.
Code snippet:
mysql_select_db($database_W3OITesting, $W3OITesting);
$yearnow = date("Y",strtotime('+1 year')).'-12-31';
$yearrecent = date("Y",strtotime('-1 year')).'-12-31';
$query_Recordset1 = "SELECT DISTINCT lname, fname, suffix, fcccall, members.member_id, MaxDateTime " .
"FROM members " .
"INNER JOIN " .
"(SELECT paid.member_id, MAX(paid.year) AS MaxDateTime " .
"FROM paid " .
"GROUP BY paid.member_id) groupedpaid ".
"ON members.member_id = groupedpaid.member_id " .
"Where (MaxDateTime < '$yearnow') AND ".
"(MaxDateTime >= '$yearrecent')" .
"ORDER BY lname, fname, suffix, fcccall";
$Recordset1 = mysql_query($query_Recordset1, $W3OITesting) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
//if a post is received handle it here
function getPostArray($array){
foreach ($array as $key => $value){
//search here for if this member is part of a family
//if not part of a family just update the payment
//record for the member with the value
try {
$query_Recordset3 = "SELECT lname, fname, suffix, `members`.member_id , `family`.member_id " .
"FROM members, family " .
"WHERE (`members`.member_id = `family`.member_id " .
"AND `members`.member_id = $key)";
echo $query_Recordset3. "<br>";
$Recordset3 = mysql_query($query_Recordset3, $W3OITesting);
$row_Recordset3 = mysql_fetch_assoc($Recordset3);
$totalRows_Recordset3 = mysql_num_rows($Recordset3);
echo $totalRows_Recordset3 . "<br>";
echo "$key => $value";
if($totalRows_Recordset3==FALSE) {//Recordset3 is always FALSE
echo " Error - " . $row_Recordset3['lname'];
}
if($totalRows_Recordset3!=0) {
echo " - A Family";
} else {
echo " - Individual";
}
echo "<br>";
}
catch(Exception $e)
{
echo "Exception: $e";
die();
}
if(is_array($value)){ //If $value is an array, get it also
getPostArray($value);
}
}
}
I do not know what I am doing wrong here. When the following query is executed I receive the following error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables
does not match number of tokens
This is my query :
SELECT id, recipe_name, ingredients, directions, user_id, category_id, country_id, name, type, size FROM recipes WHERE user_id =:user_id LIMIT:per_page OFFSET:pagination_offset
And here is the script:
$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 3;
$total_count = $this->countAll($iId); // which is 9 at this point
$pagination = new Pagination($page, $per_page, $total_count);
$pagination_offset = $pagination->offset();
$sWhereClause = "WHERE user_id =:user_id ";
$sLimitClause = "LIMIT:per_page ";
$sOffsetClause = "OFFSET:pagination_offset " ;
$aBinding = array (
':user_id' => $iUserId,
':per_page' => (int)$per_page,
':pagination_offset' => (int)$pagination_offset,
);
$sql = "
SELECT
*
FROM
recipes
" . $sWhereClause . "
" . $sLimitClause . "
" . $sOffsetClause . "
";
try{
$var = $this->db->prepare($sql);
$var->execute($binding);
return $var->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
die($ex->getMessage());
}
Thank you for any help!
You define your bindings in the array $aBinding, but then send $binding to execute. Just use the same variable consistently, and you should be fine:
$var->execute($aBinding);
Okay so I have three different types of users (Developers, Designers & Employers) all of whom have different database tables. I have successfully developed a script that can log in a user from any of the three user tables using UNION. However I have now introduced email verification on sign up so I need to test whether the 'confirmed' field (in each table) has a value of '1' to process a successful login (if the value is 0, the user will not be able to log in).
public function email_confirmed($email) {
$query = $this->db->prepare("SELECT
COUNT(developers.id) FROM " . DB_NAME . ".developers WHERE developers.email= ? AND developers.confirmed = ?
UNION SELECT COUNT(designers.id) FROM " . DB_NAME . ".designers WHERE designers.email = ? AND designers.confirmed = ?
UNION SELECT COUNT(employers.id) FROM " . DB_NAME . ".employers WHERE employers.email = ? AND employers.confirmed = ?
");
$query->bindValue(1, $email);
$query->bindValue(2, 1);
$query->bindValue(3, $email);
$query->bindValue(4, 1);
$query->bindValue(5, $email);
$query->bindValue(6, 1);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
At the moment however (using the function below), only a developer can log in. If you attempt to log in using a designer or an employer account, the error below shows. Any ideas why this is happening?
if ($users->email_confirmed($email) === false) {
$errors[] = 'Sorry, but you need to activate your account. Please check your emails.';
} else // carry on logging in user
This is your query:
SELECT COUNT(developers.id)
FROM " . DB_NAME . ".developers
WHERE developers.email= ? AND developers.confirmed = ?
UNION
SELECT COUNT(designers.id)
FROM " . DB_NAME . ".designers
WHERE designers.email = ? AND designers.confirmed = ?
UNION
SELECT COUNT(employers.id)
FROM " . DB_NAME . ".employers
WHERE employers.email = ? AND employers.confirmed = ?
It is fetching three rows, then removing duplicates, and ordering them arbitrarily. You are then reading the value (the count) from one of these rows.
Taking the approach you are taking, I think you want:
select COUNT(*)
from ((select 1
from " . DB_NAME . ".developers
where developers.email= ? AND developers.confirmed = ?
) union all
(select 1
from " . DB_NAME . ".designers
where designers.email = ? AND designers.confirmed = ?
) union all
(select 1
from " . DB_NAME . ".employers
where employers.email = ? AND employers.confirmed = ?
)
) t
I'm building a simple search algorithm and I want to break my string with spaces, and search my database on it, like so:
$search = "Sony TV with FullHD support";
$search = explode( ' ', $search );
SELECT name FROM Products WHERE name LIKE %$search[1]% AND name LIKE %$search[2]% LIMIT 6
Is this possible?
Yes, you can use SQL IN operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE you will need to use OR instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
This will works perfectly in both cases, one or multiple fields searching multiple words.
Hope this will help someone. Thanks
declare #searchTrm varchar(MAX)='one two three four';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
This has been partially answered here:
MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case.
I hope this helps.
You can try and execute below query:
SELECT name FROM Products WHERE REGEXP '.*Value1|.*Value2';
Pls note that there should not be a space before or after the pipe symbol
(|).
I know this is long time ago, but I have a solution. It can solved like this:
#intial query
query = 'SELECT var1, var2 FROM dbo.db_name WHERE'
if status :
query = query + " AND status='" + status + "'"
if type :
query = query + " AND Type='" + type + "'"
if number :
query = query + " AND Number='" + number + "'"
if cancel_request:
query = query + " AND CancelRequest='" + cancel_request + "'"
query = query + ' ORDER BY transid DESC'
cur.execute(query)
How can I update over this query
$sqlquery = UPDATE("conference",
array('area_of_expertise' => $area_of_expertise_id1,
'long_name' => $_POST['longname'],
'short_name' => $_POST['shortname'],
'description' => $_POST['textarea'],
'creator_id' => $get_id
)
);
I inserted all the need data in the conference table while making sure that it was the same data the user had chosen.
Your UPDATE query syntax is wrong.
You're not saying what table you want to update and which column of that table.
You're just saying UPDATE.
Syntax should be like :
UPDATE tableName SET column = value [ WHERE someColumn = someValue ]
Reference :
http://www.w3schools.com/php/php_mysql_update.asp
I assume you're also using PHP. Is 'UPDATE' a self-defined function? I've never come across it before.
$update = mysql_query("UPDATE conference SET area_of_expertise = '" . $area_of_expertise_id1 . "', long_name = '" . $_POST["longname"] . "', short_name = '" . $_POST["shortname"] . "', description = '" . $_POST["textarea"] . "' WHERE creator_id = " . $get_id);
I'm only assuming your table and column names by the way.
$query = "UPDATE conference SET area_of_expertise='$area_of_expertise_id1', long_name='$_POST['longname']', short_name='$_POST['shortname']', description='$_POST['textarea']' WHERE creator_id='$get_id'");
$update_value = mysql_query($query);
Hope that Helps.