Codeigniter query builder using implode function in where_in - mysql

Here is my normal sql query using implode function:
SELECT * from search_result WHERE skills IN ('".implode("','",$s_id)."');
Now I want to convert this to codeigniter form. I tried the following code but it fails
$this->db->from('search_result');
$this->db->where_in('skills','".implode("','",$s_id)."');
$query = $this->db->get();
Here is my $s_id array:
Array ( [0] => 2D Design [1] => 3D Design [2] => 3D Modelling )
So anyone please help me to do this. Thanks in advance :)

Official Doc say's
$names = array('Frank', 'Todd', 'James'); # Data Array
$this->db->where_in('username', $names); # passing array
Try like below
Method 01(recommended )
$this->db->from('search_result');
$this->db->where_in('skills',$s_id);
$query = $this->db->get();
Method 02
$this->db->from('search_result');
$this->db->where_in('skills',implode("','",$s_id));
$query = $this->db->get();
Whats wrong on this line
$this->db->where_in('skills','".implode("','",$s_id)."');
don't wrap function with ' or " quotes. Then it will get save as STRING value to DB.
Links
where_in clause in codeigniter.com

You can just write this :
$this->db->from('search_result');
$this->db->where_in('skills', $s_id);
$query = $this->db->get();
Official doc
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

Related

pdo prepared statements exit with invalid parameter number

I have the following query:
$sql="INSERT INTO form_6 SET
Project-name=:Project-name,
Project-manager-gruppo-CDT=:Project-manager-gruppo-CDT,
Short-description=:Short-description,
Status=:Status,
Dependency-with-BB-Pj=:Dependency-with-BB-Pj,
Critical-issues=:Critical-issues"
and the following array of data to be inserted:
Array (
[:Project-name] => test
[:Project-manager-gruppo-CDT] => jack
[:Short-description] => simple project
[:Status] => on going
[:Dependency-with-BB-Pj] => yes
[:Critical-issues] => problems trying to insert data
)
and this is the code that I am using to run the query:
try{
$stmt = $pdo->prepare($sql);
$stmt->execute($values_array);
}
catch(PDOException $Exception){
$message=$Exception->getMessage();
$status=500;
//ho avuto un problema e mi fermo
die(json_encode(array('status'=>$status,'message' => $message)));
}
I really am not able to see why this terminates with the following exception:
Invalid parameter number: parameter was not defined
usually this comes from typos between the query and the array or using the same placeholder two times. But typos are excluded since I build the query and the array together using a foreach:
$values_array=array();
$sql = "INSERT INTO $tabella SET ";
foreach ($_POST as $key=>$value){
$sql .= $key.'=:'.$key.',';
$values_array[":$key"]=$value;
}
$sql=rtrim($sql,',');
echo $sql; //this echoes the query at the beginning of the question
print_r($values_array); //this echoes the array at the beginning of the question
What am I missing?
You can't use - in parameter names. When you write :Project-name it's equivalent to :Profile - name, so it's expecting a parameter named :Profile, and then trying to subtract the column name from that.
Replace the - with _ in the placeholder.
Also, if a column name contains -, you need to put the name in backticks. See When to use single quotes, double quotes, and backticks in MySQL
$values_array=array();
$sql = "INSERT INTO $tabella SET ";
foreach ($_POST as $key=>$value){
$placeholder = str_replace('-', '_', $key);
$sql .= "`$key` = :$placeholder,";
$values_array[":$placeholder"]=$value;
}

Wordpress MySQL result resource is not valid

I have wp_places custom table and I am getting this when I am printing array:
[0] => stdClass Object
(
[home_location] => 24
)
[1] => stdClass Object
(
[home_location] => 29
)
Now I want to implode value like this way (24,29) but in my code I am getting this error:
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
My Code
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bgroup[] = implode(',',$row);
}
echo implode(',',$bgroup);
Any ideas or suggestions? Thanks.
$wpdb->get_results() already do the fetching for you, you don't need to call mysql_fetch_array
Given what you want to do, your code should look like this :
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
foreach ($result as $location) {
$bgroup[] = $location->home_location;
}
echo '('.implode(',',$bgroup).')';
It's an PHP object that contains results, it isn't a MySQL Result.
Looking at the docs, it should be used like
foreach ($result as $row) {
$bgroup[] = $row->home_location;
}
echo implode(',',$bgroup)

Highstock mysql json compare multiple series

Please help to create a query!
This is a working example of my query Retrieve data as JSON using PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("admin_accounting", $con);
$result = mysql_query("SELECT unix_timestamp(date), sum(ksi2k) FROM accounting where lhc_vo like 'ops' group by year(date), month(date)");
$rows = array();
$rows['type'] = 'area';
$rows['name'] = 'Ops';
while($r = mysql_fetch_array($result)) {
$rows['data'][] = $r[0]*1000;
$rows['data'][] = $r[1];
array_push($rows);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
The JSON results look like this:
{"type":"area","name":"Ops","data":[1167664515000,0,1170342915000,0,1172762115000,0,1175436915000,0,1178028915000,0]}
But I need the JSON results should look like this:
{"type":"area","name":"Ops","data":[[1167664515000,0],[1170342915000,0],[1172762115000,0],[1175436915000,0],[1178028915000,0]]}
I would be very grateful for the help
while($r = mysql_fetch_array($result)) {
$rows['data'][] = array($r[0]*1000, $r[1]);
}
In addition to my other answer, you ought to consider switching away from the ancient (and now deprecated, as of PHP v5.5) ext/mysql. Here is an example using PDO, in which you can see how simple your problem becomes:
<?php
$con = new PDO(
'mysql:hostname=localhost;dbname=admin_accounting',
'user',
'password'
);
$result = $con->query('
SELECT 1000*UNIX_TIMESTAMP(date), SUM(ksi2k)
FROM accounting
WHERE lhc_vo LIKE "ops"
GROUP BY YEAR(date), MONTH(date)
');
print json_encode([
'type' => 'area',
'name' => 'Ops',
'data' => $result->fetchAll(PDO::FETCH_NUM)
]);
?>
Note that:
I have moved the multiplication into the database layer in order that I can simply call fetchAll() to obtain the resulting array;
MySQL will select an indeterminate value from amongst those in each group for the first column in the resultset; should this be undesirable, you will need to apply a suitable aggregate function to the reference to the date column; and
I have used the short array syntax, which is only available from PHP v5.4—if you're using an earlier version, you will need to replace the [ … ] of the argument to json_encode() with array( … ).

Saving the output of a Perl SQL query to a hash instead of an array

I'm trying to add an argument to the end of a command line, run that search through a MySQL database, and then list the results or say that nothing was found. I'm trying to do it by saving the query data as both hashes and arrays (these are exercises, I'm extremely new at PERL and scripting and trying to learn). However, I can't figure out how to do the same thing with a hash. I do want the SQL query to complete, and then write the output to a hash, so as not to invoke the While function. Any guidance would be appreciated.
#!/usr/bin/perl -w
use warnings;
use DBI;
use Getopt::Std;
&function1;
&function2;
if ($arrayvalue != 0) {
print "No values found for '$search'"."\n"};
sub function1 {
getopt('s:');
$dbh = DBI->connect("dbi:mysql:dbname=database", "root", "password")
or die $DBI::errstr;
$search = $opt_s;
$sql = $dbh->selectall_arrayref(SELECT Player from Players_Sport where Sport like '$search'")
or die $DBI::errstr;
#array = map { $_->[0] } #$sql;
$dbh->disconnect
or warn "Disconnection failed": $DBI::errstr\n";
}
sub function2 {
#array;
$arrayvalue=();
print join("\n", #array, "\n");
if(scalar (#array) == 0) {
$arrayvalue = -1
}
else {$arrayvalue = 0;
};
}
Please see and read the DBI documentation on selectall_hashref. It returns a reference to a hash of reference to hashes.
Use Syntax:
$dbh->selectall_hashref($statement, $key_field[, \%attri][, #bind_values])
So here is an example of what/how it would be returned:
my $dbh = DBI->connect($dsn, $user, $pw) or die $DBI::errstr;
my $href = $dbh->selectall_hashref(q/SELECT col1, col2, col3
FROM table/, q/col1/);
Your returned structure would look like:
{
value1 => {
col1 => 'value1',
col2 => 'value2',
col3 => 'value3'
}
}
So you could do something as follows for accessing your hash references:
my $href = $dbh->selectall_hashref( q/SELECT Player FROM
Players_Sport/, q/Player/ );
# $_ is the value of Player
print "$_\n" for (keys %$href);
You can access each hash record individually by simply doing as so:
$href->{$_}->{Player}
Cribbing from the documentation:
$sql = $dbh->selectall_hashef("SELECT Player from Players_Sport where Sport like ?", 'Players_Sport_pkey', $sport_like_value);
my %hash_of_sql = %{$sql};

How to use agregate Mysql functions with CakePHP

There is a way to use agregate functions with cakephp? like sum() or avg() with find() method.
UPDATE:
I missed a line in the book
array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');
Showing the basic structure for doing that.
Thanks for the help
In the fields parameter of a find method call, you may pass the field processed by an aggregated function. Example:
$Model->find('all',
array(
'anything' => array(/* */),
'fields' => array(
'SUM (Model.attribute) AS total',
'OTHERFUNCTION(OModel.other_attribute) AS other'
),
'otherthing' => array(/* */)
)
);
In exactly the same way, since CakePHP is just a PHP framework.
<?php
// Make a MySQL Connection
$query = "SELECT type, SUM(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>