wordpress $wpdb sql querying - sql

I'm working on a WordPress plugin, and I need some help in this.. in this situation, i have already created a table called "wp_pfot", and a row called "title" in that table. I want to be able to check if a value in "title" doesn't exists, and if it doesn't exist, then perform an action. I've already tried this but it doesn't seem to be working.
global $wpdb
$table_name = $wpdb->prefix . "pfot";
$title = "some text";
if(!$wpdb->get_row("SELECT title FROM $table_name WHERE title = '" . $title . "'", 'ARRAY_A')) {
//do something
}
any help would be much appreciated!! thanks...

ARRAY_A is a constant, not a string.
global $wpdb
$table_name = $wpdb->prefix . "pfot";
$title = "some text";
if($wpdb->get_row("SELECT title FROM $table_name WHERE title = '$title'", ARRAY_A)) {
//do something
}

Related

How can I convert this to use PDO?

I would like to use PDO for selecting (searching) a database.
The search 'form' has MULTIPLE fields that can be used.. 1 or many can be filled in to help refine the search. (or there can be many o them left blank/empty)
here is what I have been using (locally):
//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";
mysql_connect($db_host,$db_username,$db_password);
#mysql_select_db($db_database) or die("Unable to connect to database.");
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('first', 'trialdate', 'wcity', 'wstate', 'plantif');
$conditions = array();
//loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
//build the query
$query = "SELECT * FROM myTable ";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' OR ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysql_query($query);
if(isset($_POST['submit'])) {
while($row = mysql_fetch_array($result)) {
echo $row['first'] . "<br />"; //individual value
//build panels that displays everything from row..etc
}
}
}
this has been working fine... but I'd like convert to using the PDO approach.
I gave it a few tries...but am missing something here..
heres what I've tried so far..
//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";
//PDO DB connection
$conn = new PDO('mysql:host='.$db_host.'dbname='.$db_database.'charset=utf8', $db_username, $db_password);
if(isset($_POST['submit'])) {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE first LIKE :first OR trialdate LIKE :trialdate OR wcity LIKE :wcity OR wstate LIKE :wstate OR plantif LIKE :plantif');
//build query placeholders (*note: use bindValue for $_POST values)
$stmt->bindValue(':first', '%' . $_POST['first'] . '%');
$stmt->bindValue(':trialdate', '%' . $_POST['trialdate'] . '%');
$stmt->bindValue(':wcity', '%' . $_POST['wcity'] . '%');
$stmt->bindValue(':wstate', '%' . $_POST['wstate'] . '%');
$stmt->bindValue(':plantif', '%' . $_POST['plantif'] . '%');
$stmt->execute();
foreach ($stmt as $row) {
// do something with $row
echo $row['first'] . "<br />"; //individual value
}
}
I could use help on getting the PDO example working with a displayed result/row/value?

Issue in making appear all database table field names

I have this code which i use in order to make appear all the names of a table of a database.
It used to work... but suddenly it won't make appear anything..
Could you please take a look?
I'm working with SQL.
$section = "SELECT * FROM forma";
$res = odbc_exec($connection, $section) or die(odbc_error());
$firstrow = false;
while ($row = odbc_fetch_array($res)){
if (!$firstrow) {
foreach ($row as $column => $value) {
echo "<label> " . $column . "</label>";
echo "<input type='checkbox' name='data[]' value='" . $column . "' /><br/><br/>";
}
$firstrow = true;
}
}
Thanks
This is a fairly nasty way of retrieving the column names for a table. What it is doing is reading all the data in the table, ignoring the result set and only using it for the column names. What is happening however is that the table is empty and so nothing is being returned at all.
You need to amend the query to look at the meta data rather than the table itself. You will need to rework it. This SQL will retrieve the column names for that table for you...
Select Columns.Name
From Sys.Columns
Where Object_Name(Columns.Object_id) = 'forma'
Order By Columns.Column_Id;
After that you will need to rejig your code to take advantage of it.

opencart getcategories function goes into infinite loop

I have an opencart shop with around 1300 categories and i'm not able to insert a new category or edit the existing category. I have installed pagination function, but it speeds up only category view. i did some debugging and found that the below function goes into an infinite loop once i click insert or edit inside the admin panel. Can anyone help me how to fix this
public function getCategories($parent_id = 0) {
$category_data = $this->cache->get('category.' . (int)$this->config->get('config_language_id') . '.' . (int)$parent_id);
if (!$category_data) {
$category_data = array();
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY c.sort_order, cd.name ASC");
foreach ($query->rows as $result) {
$category_data[] = array(
'category_id' => $result['category_id'],
'name' => $this->getPath($result['category_id'], $this->config->get('config_language_id')),
'status' => $result['status'],
'sort_order' => $result['sort_order']
);
$category_data = array_merge($category_data, $this->getCategories($result['category_id']));
}
$this->cache->set('category.' . (int)$this->config->get('config_language_id') . '.' . (int)$parent_id, $category_data);
}
return $category_data;
}
First Solution:
Do you also have Category Descriptions in database? If so, these so many descriptions being loaded by MySQL may be making burden over server. Try optimize the Query, select only required columns, you may change query as under:
$query = $this->db->query("SELECT c.category_id, cd.name FROM ...
Second Solution
You can do one more debug trick which once solved my problem. Add an echo statement:
echo $result['name'];
$category_data = array_merge($category_data, $this->getCategories($result['category_id']));` `
This way you'll get to know the exact location of the category where process gets hanged. There may be some problem with that particular category only.
Third Solution
Try changing
'name' => $this->getPath($result['category_id'], $this->config->get('config_language_id')),
To:
'name' => $result['name'],
Hope this helps.
I have a current but not permanent solution that worked for me... I dont know whether it's the right way to do, but it works for me.I changed the query to this
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c ORDER BY c.parent_id,c.sort_order");
And commented off
//$category_data = array_merge($category_data, $this->getCategories($result['category_id']));
This currently works for me, but i don't know whether it's the correct way or not. Thanks for the quick help everyone.

how to use like query in drupal

How to write SQL LIKE Query in drupal ,
SELECT title FROM { node } WHERE type='%s'
i want to add the LIKE CONDITION IN THAT
SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'
i think i writtern wrong like query formnat, can rewrite and tell me,
Just use % to escape.
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
while ($row = db_fetch_object($result)) {
// do stuff with the data
}
Node type does not need escaping.
And here is an example with how to use LIKE in a dynamic query (Drupal 7 Only):
$query = db_select('node', 'n')
->fields('n', array('title'))
->condition('type', 'my_type')
->condition('title', '%' . db_like(search_string) . '%', 'LIKE');
$result = $query->execute()->fetchCol();
db_like() is used to escapes characters that work as wildcard characters in a LIKE pattern.
drupal_query replace %% to % and %s to value string
so your code will be
$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
OK, so you want the LIKE operator to refer to the title column. Use this query:
$sql = "SELECT title FROM node WHERE type='%s' AND title LIKE '%S%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
This is because the LIKE operator requires a column name to be specified. Otherwise, your database doesn't have any idea what value you want to perform the comparison on. See here.

getting data from 2 different table with JOIN sql. Codeigniter

I use codeigniter, and I need to get data from 2 different table. for now it returns data only from works_image table. how can I get data from both 2 table ?
thanks a lot!!
$this->db->select('works_image.*', 'works.*');
$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();
foreach ($result->result() as $row) {
echo " # " . $row->id . " - " . $row->thumb . " - " . $row->wname . "";
}
As long as you're doing a SELECT * (Why is this a bad idea?), you shouldn't need to specify tables with the call to select(). It will select all fields by default.
$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();
Should work fine.
Instead, what you really should be doing, is specifying exactly which fields you need:
$this->db->select('works_image.id, works_image.name, works_image.id_work, works.id, works.name'); // (or whichever fields you're interested in)
$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();
This way you can be sure that (a) you're not pulling unnecessary data from your DB, and (b) your code won't break if/when you modify your DB schema.
This post should answer your question: http://www.whypad.com/posts/codeigniter-activerecord-join-tip/178/
In short, you need to rewrite your select statement from
$this->db->select('works_image.*', 'works.*');
to this:
$this->db->select('works_image.*, works.*');
Note that this was the first result on Google for 'CodeIgniter join'. Try Googling your questions first. You can often get yourself a faster answer :)
You should be to write below code
$this->db->select('works_image.*', 'works.*');
$this->db->from('works_image');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();
foreach ($result->result() as $row) {
echo " # " . $row->id . " - " . $row->thumb . " - " . $row->wname . "
";
}
I think that you get your result