special mysql query from a joomla website - mysql

I have this context:
CREATE TABLE `atdees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`params` text NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `atdees` (`id`, `params`) VALUES
(1,'{"field282":"0","field347":"1"}'),
(2,'{"field282":"0","field347":"0"}'),
(3,'{"field282":"0"}');
I have to extract from the table the rows where :
an atdee must have the string '"field282":"0"'
an atdee has the string '"field282":"0"' but not the string '"field347":"0"'
an atdee has both string '"field282":"0"' and '"field347":"0"'
In other words I have to extract the Id 2 and 3.
Thank you.
Ps: Sorry for my english, I am not a native speaker ;)
edit: well i found my query
SELECT id
FROM atdees
WHERE
INSTR(`params`, '"field282":"0"') > 0 and
( params LIKE '%"field347":"0"%' OR
INSTR(`params`, '"field347"') = 0 )

If it's simply getting data from the database, then you can use something like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__atdees'));
$query->where($db->quoteName('params') . " = " . $db->quote('"field282":"0"') . "OR" . $db->quote('"field347":"0"'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result ) {
echo "<p>" . $result->id . "</p>";
}
Not sure if the database table is for a Joomla extensions but if so, keep it as #__atdees in your query, else change to atdees
Hope this helps

Related

Wordpress include post associated to specific term in search results

I'm working on a custom search engine for my WordPress site. The DB for the project is pretty big ( 300k+ posts ) so performance is key.
I have a searchbar returning posts ('clients' & 'professionnels') and i'm trying to limit search results to post title and terms name from 'specialites' taxonomy. So far i'm using a filter (https://stackoverflow.com/a/59537500/19181295).
function and_extend_search( $search, &$wp_query ) {
global $wpdb;
if ( empty( $search ))
return $search;
$terms = $wp_query->query_vars[ 's' ];
$exploded = explode( ' ', $terms );
if( $exploded === FALSE || count( $exploded ) == 0 )
$exploded = array( 0 => $terms );
$search = '';
foreach( $exploded as $tag ) {
$search .= " AND (
($wpdb->posts.post_title LIKE '%$tag%')
OR EXISTS
(
SELECT
*
FROM
$wpdb->term_relationships
LEFT JOIN
$wpdb->terms
ON
$wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id
WHERE
$wpdb->terms.name LIKE '%$tag%'
AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
)";
}
return $search;
}
add_filter('posts_search', 'and_extend_search', 500, 2);
The filter is pretty good but it's searching inside all taxonomies. What i want is keeping the filter but only return results in terms associated with 'specialites' taxonomy.
Can you guys help me please ? :)
from Comment
CREATE TABLE xmo_term_relationships (
object_id bigint(20) unsigned NOT NULL DEFAULT 0,
term_taxonomy_id bigint(20) unsigned NOT NULL DEFAULT 0,
term_order int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (object_id,term_taxonomy_id),
KEY term_taxonomy_id (term_taxonomy_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
If the tables are big and you want performance,
Do not use LIKE with leading wildcards
Do consider using FULLTEXT index(es).
Do install this plugin: WP Index Improvements
Get rid of the second if statement; $exploded will be as you want it anyway.
Try to avoid ORs; they do not Optimize well.
After you have done those, come back with some revised queries; I will probably have more suggestions. At that time, please provide SHOW CREATE TABLE and EXPLAIN.

how to delete huge mysql rows depending on not equal

the problem that its a huge amount the query would be like
DELETE FROM `members` WHERE `membership` = 'C' AND (`id` != '1' AND `id` !='2' AND ...... thousands of ids );
how I can do that ?
I did also WHERE id NOT IN ("1","2"); but also did not work
can I use loop or something like that
the IDs that I want to keep and do not delete comes from another table contains a field holds the user ID that I don't want to delete I used PHP script to help me to generate the SQL query
like
<?php
require_once("inc.php");
$realty_uids = $db->query("SELECT `uid` from `realty2` ORDER BY `uid`");
$r = $db->fetch_assoc($realty_uids);
while($r = $db->fetch_assoc($realty_uids)){
$array[] = $r['uid'];
}
$input = array_unique($array);
echo "DELETE from `members` WHERE `membership` = 'C' ";
foreach($input as $key => $value){
echo " AND `id` != '".$value."' <br>";
}
echo ";";
DELETE FROM `members` WHERE `membership` = 'C' AND NOT EXISTS (SELECT at.uid FROM `realty2` at WHERE at.uid = `members`.id);
This way worked good thanks for every one tried :)

Csv upload to mysql in perl

I am new in perl programming language. Can you please guide how to write csv upload into mysql database.
I have following table & csv file format
Create Table:
CREATE TABLE consumeruser (
ConsumerId int(10) NOT NULL AUTO_INCREMENT,
ConsumerName varchar(45) DEFAULT NULL,
ConsumerMobNo varchar(10) DEFAULT NULL,
PRIMARY KEY (ConsumerId)
) ENGINE=InnoDB AUTO_INCREMENT=4494 DEFAULT CHARSET=latin1
Csv file example:
4495,Sanchita Mehra,999999999
4496,Rupesh Shewalkar,88888888
4497,Aditya Mishra,111111111
Csv upload should be on basis of mobile number, suppose if table already contain mobile 111111111 Then that row should be skip. Means all mobile numbers should be check with existing data, if it is already in database that row should not be insert in database & rest of inserted into database.
You can check for the count of the row to see if the data is already present and then continue to next statement if its present. The implementation is for SQLite and you can change it to MySQL.
#!/usr/bin/perl
use Modern::Perl '2012';
use DBD::SQLite;
use warnings;
my $dbh = DBI->connect("dbi:SQLite:dbname=Consumer");
while(<DATA>){
chomp;
my ($id, $name, $MobNo) = split /,/;
my $query = "select count(*) from consumeruser where ConsumerMobNo = ?";
my $sth = $dbh->prepare($query);
$sth->execute($MobNo);
my $row = $sth->fetch();
next if(#$row > 0);
my $insertStatement = "insert into consumeruser values(?,'?',?)";
$sth = $dbh->prepare($insertStatement);
$sth->execute($id,$name,$MobNo);
}
__DATA__
4495,Sanchita Mehra,999999999
4496,Rupesh Shewalkar,88888888
4497,Aditya Mishra,111111111
4498,Aditya,111111111
Edit:
For fetching all the mobile numbers in the array. You can do like this.
my #MobileNumbers;
my $mobileNumberQuery = "select ConsumerMobNo from consumeruser";
my $sth = $dbh->prepare($mobileNumberQuery);
$sth->execute();
while(my $row = $sth->fetch()){
push #MobileNumbers, #$row;
}
Please refer to perldoc DBI for various ways of accessing the results.

Error: Duplicate entry '0' for key 'PRIMARY'

I can't resolve my problem, this is the error from mysql that I'm getting:
I can edit and update my data when I've got one record in the database but when I add two rows, I get the error.
Some pictures from database
And when I change the row, row ID goes down to 0 and that's is a problem as I can't edit other rows.
CREATE TABLE `dati` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`value1` varchar(255) NOT NULL,
`value2` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 PACK_KEYS=1
Update Code:
<?php // Izlabot datus datubāzē!
$titletxt = $_POST['title_edit'];
$value1 = $_POST['value1_edit'];
$value2 = $_POST['value2_edit'];
if(isset($_POST['edit'])){
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$sql="UPDATE dati SET ID='$ID',title= '$titletxt',value1='$value1',value2='$value2' WHERE 1";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo '<script>
alert(" Ieraksts ir veiksmīgi labots! ");
window.location.href = "index.php";
</script>';
mysqli_close($con);
}
?>
From form:
<?php
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM dati");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><input id='titled' type='text' name='title_edit' value='" . $row['title'] . "'></td>";
echo "<td><input id='value1d' type='text' name='value1_edit' value='" . $row['value1'] . "'></td>";
echo "<td><input id='value2d' type='text' name='value2_edit' value='" . $row['value2'] . "'></td>";
echo "<input type='hidden' name='id' value='" . $row['ID'] . "'>";
echo "<td><button name='edit' id='edit_btn' class='frm_btns' value='" . $row['ID'] . "'>Edit</button></td>";
echo "</tr>";
}
mysqli_close($con);
?>
It couldn't read the value of ID, as 0 was returned.
For those arriving at this question because of the question title (as I did), this solved my problem:
This error can indicate that the table's PRIMARY KEY is not set to AUTO-INCREMENT, (and your insert query did not specify an ID value).
To resolve:
Check that there is a PRIMARY KEY set on your table, and that the PRIMARY KEY is set to AUTO-INCREMENT.
How to add auto-increment to column in mysql database using phpmyadmin?
The error log like (In my case), I'm using Aurora DB:
PHP message: WordPress database error Duplicate entry '0' for key 'PRIMARY' for query INSERT INTO `date173_postmeta
How to fix it using MySQL Workbench:
1- Connect at your DB, and go to the table with the issue, in my case date173_postmeta
2- Select the tools icon:
3- In the windows/tab at right, select the AI checkbox and click on Apply button:
Following the last steps my issues gone.
The problem is that your code attempts to change every row in the data changing the primary key to the value in $ID. This is not set anywhere in your code, and presumably is being cast as 0
$sql="UPDATE `dati` SET `ID`='$ID',`title`=
'$titletxt',`value1`='$value1',`value2`='$value2' WHERE 1";
The primary key value should be sent to the form and returned so it can be processed by your code, but the value should be retained, hence....
$sql="UPDATE `dati` SET `title`=
'$titletxt',`value1`='$value1',`value2`='$value2' WHERE `ID`=$ID";
You should also read up on MySQL injection - even after you've fixed the errors here, anyone can do just about anything they want with your database.
Try this:
ID int(11) PRIMARY KEY AUTOINCREMENT(1,3)
The problem in set ID = $ID
Try removing it so the code should be
$sql="UPDATE `dati` `title`= '$titletxt',`value1`='$value1',`value2`='$value2' WHERE 1";
Be sure to change this where cause it'll update ever row with these values
Just make sure that your primery keys are also A-I.
I'd been struggling to fix this. My tables had auto increment (AI) switched on
Before I started tinkering with records I tried a simple repair in phpMyAdmin.
Go to the SQL tab and run each command in turn.
REPAIR TABLE wp_options
REPAIR TABLE wp_users
REPAIR TABLE wp_usermeta
This did the trick for me and allowed me to login.
i am using phpmyadmin,
so go to db , search for wp_postmeta tabel
add AI(auto-increment) to meta_id
save the changes

MYSQL copy row to another identical table with AUTO_INCREMENT id field

I have a movie database where movies are inserted into a table named titles with an AUTO_INCREMENT primary key named titles_id. Users can submit movies anonymously which are inserted into a separate identical table named titles_anon. After reviewing entries in titles_anon I want to insert them into titles but the id column is causing problems
I tried this:
INSERT INTO titles SELECT * FROM titles_anon WHERE
title_id='$title_id';
I either get a duplicate key error, or if the title_id does not already exist in titles it inserts OK but uses the titles_anon id instead of a new AUTO_INCREMENT value which I want.
How do I copy a row between tables when both tables have an AUTO_INCREMENT primary key?
INSERT INTO titles
(column_name1, column_name2, column_name3, column_name4,...)
SELECT title_id, col2, col3, col4,..
FROM titles_anon
WHERE title_id = '$title_id';
You define your fields in SELECT, but omit the PK and add the same fields to INSERT!
You can omit the id column completely, let mysql generate it for you. This need a little longer SQL to specify the exact columns you want to insert.
INSERT INTO titles (columns-other-than-the-primary-key)
SELECT columns-of-the-same-order FROM titles_anon
In PHP you can do something similar to:
$rs = mysql_query("select * from table_orig where RowID=$IDToCopy",$db_conn);
$row = mysql_fetch_assoc($rs);
$sql = '';
$fields = '';
foreach($row as $k => $v){
if($k == "RowID") continue;
$sql .= ",'$v'";
$fields .= ",$k";
}
$sql = "insert into table_copy (".substr($fields,1).") values (".substr($sql,1).")";
mysql_query($sql,$db_conn);
/* copy table with primary key to another table */
$table_old='colaboradores'; // your table old
$table_new='colaboradores2'; //your table new
// sql all columns withou primary key (column_key <> 'pri'
$rs=mysql_query("select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name = '$table_old' and column_key <> 'pri' AND
table_schema = 'your database'");
// get all columns
$rows = mysql_fetch_assoc($rs);
$fields = '';
// mount fields in line
foreach ($rows as $k => $v) {
$fields .= ",$v[0]";
}
// remove first comma
$fields = substr($fields,1);
echo "Sintaxe for Create table in Mysql";
echo "CREATE TABLE $table_new SELECT $fields FROM $table_old ";
echo "Sintaxe for Insert from old table to new table Mysql";
echo "INSERT INTO $table_new $fields SELECT $fields FROM $table_old";