Better way to do this MySQL query? - mysql

This is what I'm doing now, how to do this without resorting to a subquery and without the php. I can just run it inside phpmyadmin directly:
<?php
$query = mysql_query(" SELECT node_id FROM embeds ");
while($row = mysql_fetch_assoc($query)) {
$node_id = $row['node_id'];
mysql_query(" INSERT INTO node_teaser(node_id, content) VALUES('$node_id', 'This is the teaser!') ");
}
?>

INSERT INTO node_teaser(node_id, content)
SELECT node_id, 'This is the teaser!' FROM embeds;

Related

Copy only unique entries from one table to another MySQL

I'm trying to create scheduled auto-updater for MySQL DB. The script I use is shown below. It's idea is to insert only unique products from table wp_posts to table export_copy. But this one inserts nothing.
Please help me to fix the script.
INSERT INTO `export_copy`(`name`, `link`)
SELECT p.post_title, p.guid
FROM wp_posts p
WHERE NOT EXISTS (
SELECT *
FROM export_copy, wp_posts
WHERE export_copy.id=wp_posts.ID)
Your query will never work!
Since your table's name is "wp_posts" ,it seem you want copy data from wordpress table to your own
you can handle this by php, firt you must fetch data from table and save that to an array, then export array to insert query
$link = mysqli_connect(Your_HOST , Your_User , YOUR_Pass, DB_NAME);
$q = "SELECT p.post_title, p.guid FROM wp_posts p WHERE NOT EXISTS ( SELECT * FROM export_copy, wp_posts WHERE export_copy.id=wp_posts.ID)";
$result = mysqli_query($link, $q);
$i=0;
while($row=mysqli_fetch_assoc($result))
{
$a[$i]['name'] = $row['post_title'];
$a[$i]['link'] = $row['post_title'];
$i++;
}
$q = '';
foreach($a as $a)
$q .= "('".$a['name']."','".$a['link']."'),";
$q = substr($q,0, (strlen($q)-1));
$q = "INSERT INTO `export_copy`(`name`, `link`) VALUES " . $q;
$result = mysqli_query($link, $q);

SQL - SELECT with WHERE statement return false despite present field in table

I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";

Select multiple values from multiple rows

Cant figure out how to get this result:
ProductID Variantno
53121 5197, 5198,5199
From this data collection.
ProductID Variantno
53121 5197
53121 5198
53121 5199
Tried with group by but no good result, total sql noob...
Try this..
SELECT
ProductID,
GROUP_CONCAT(Variantno)
FROM tbl
GROUP BY ProductID
select ProductID , group_concat(Variantno)
from table
group by ProductID
Try this:
WITH cte AS (
SELECT
ProductID,
CAST('<r>' + REPLACE(variantNo, ',', '</r><r>') + '</r>' AS XML) AS VariantNos
FROM TestTable
)
SELECT
ProductID,
xTable.xColumn.value('.', 'VARCHAR(MAX)') AS VariantNo
FROM cte
CROSS APPLY VariantNos.nodes('//r') AS xTable(xColumn)
Without showing your code and database. I assumed that you are working with php and mysql.
I have run and tested this code and it works. that means it will work for you. my connection is PDO. Give me a shout if are still having issues
<?php
// pdo connection
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'root90' // password
);
?>
<?php
Echo 'Data Output:<br>';
include("pdo.php");
$result = $db->prepare("SELECT * FROM product where id='123'");
$result->execute(array());
while ($r = $result->fetch())
{
//$data = htmlentities($r['product'], ENT_QUOTES, "UTF-8");
?>
<?php echo htmlentities($r['product'], ENT_QUOTES, "UTF-8");?>,
<?php } ?>

joomla database select and insert query

i am trying to insert another info to joomla (2.5.7) database after user is registered. The user chooses his usergroup and I want the insertion to happen only when the user is in a specific group. So I am trying to use this code to get the group data from the databse first to be used in the insert query. Now it is just a testing ground, later this retrieved value be used in if statement.
This is the code:
function onUserAfterSave($user, $isnew, $success, $msg)
{
if ($isnew && $success) {
$db = &JFactory::getDBO();
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$user['id'];
$db->setQuery($query);
$group = $db->loadResult();
$db->setQuery( 'INSERT INTO #__user_profiles (ordering) VALUES ('.$group.')' );
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
return $this->onAfterStoreUser($user, $isnew, $success, $msg);
}
and this is the error I am getting upon the failed registration:
Column count doesn't match value count at row 1 SQL=INSERT INTO std13_user_profiles (ordering) VALUES ()
If I read it correctly, it means that the select statement is not returning anything but why? Thank you for your help.
UPDATE:
if ($isnew && $success) {
$db = &JFactory::getDBO();
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$userId;
$db->setQuery($query);
$group = $db->loadResult();
$query2 = "INSERT INTO #__user_profiles (ordering) VALUES ('".$group."')";
$db->setQuery($query2);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
with this code, I don't get any errors and the user is registered and the values are inserted. However the $group is always 0 and based on the value is only 1 or 3 in k2_users table, I am guessing that it returns nothing. I think it may be because the registered user is not stored in the databse yet and it doesn't have his ID yet to look for the group?
UPDATE2:
if ($isnew && $success) {
$count = JRequest::getVar('gender');
if($count == 3) {
$db = &JFactory::getDBO();
$alias = $user['name'];
$table = array(
' '=>'-', 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'ě'=>'e', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'R'=>'R', 'r'=>'r', " "=>'-', '"'=>'-'
);
$string = strtr($alias, $table);
$alias_low = strtolower($string);
$query = "INSERT INTO #__menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','".$user['name']."','".$alias_low."','".$alias_low."',
'index.php?option=com_k2&view=itemlist&layout=user&id=".$user['id']."&task=user','component',1,1,10012,1)";
$db->setQuery($query);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
}
OKAY! I got it working so now I can insert new menu every time a user is created, however th activation link is not created and the registration says that it failed. This is the error:
Duplicate entry '0-1-vojtech-plesner-' for key 'idx_client_id_parent_id_alias_language' SQL=INSERT INTO std13_menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','Vojtěch Plešner','vojtech-plesner','vojtech-plesner', 'index.php?option=com_k2&view=itemlist&layout=user&id=2789&task=user','component',1,1,10012,1)
The client_id, parent_id and language have values of 1,1 and * abd they are in all the rows so why is it saying it is duplicate?
You need to update that query to 2.5 style.
http://www.theartofjoomla.com/home/9-developer/135-database-upgrades-in-joomla-16.html
is a good article.
You definitely seem to be missing
$query = $db->getQuery(true);
not to mention that you are using & for an object. That usage will generate strict errors.
You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT #__k2_users.group
FROM #__k2_users
WHERE userID = " . user['id']
";
But doesn't #__user_profiles have other columns like the user id?
Also You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT "YOURJOOMLADBPREFIX"_k2_users.group
FROM "YOURJOOMLADBPREFIX"_k2_users
WHERE userID = " . user['id']
";

Limit and order by a mysql_query

The below script works fairly well to insert different rss feeds into a mysql dbase, echoeing out a few items on a website. But when I try to order and limit in 'mysql_query' things stop to work. I suspect ORDER BY and LIMIT have been placed into the wrong position, but the only possibility I see is to place them into mysql_query. Anybody who knows?
$feeds = array('https://www.ictu.nl/rss.xml', 'http://www.vng.nl/smartsite.dws?id=97817');
foreach( $feeds as $feed ) {
$xml = simplexml_load_file($feed);
foreach($xml->channel->item as $item)
{
$date_format = "j-n-Y"; // 7-7-2008
echo date($date_format,strtotime($item->pubDate));
echo ' ';
echo ' ';
echo ''.$item->title.'';
echo '<div>' . $item->description . '<br><br></div>';
mysql_query("INSERT INTO rss_feeds (id, title, description, link, pubdate)
VALUES (
'',
'".mysql_real_escape_string($item->title)."',
'".mysql_real_escape_string($item->description=htmlspecialchars(trim($item->description)))."',
'".mysql_real_escape_string($item->link)."',
'".mysql_real_escape_string($item->pubdate)."')")ORDER BY 'title' LIMIT 0,10;
}
}
ORDER BY and LIMIT are not used with INSERT statements, they need to be used with SELECT statements.
I am not sure about the mysql_query and the notation. Still something wrong.
$selSQL = SELECT * FROM rss-feeds ORDER BY 'title';
$insSQL = "INSERT INTO 'rss_feeds' (id, title, description, link, pubdate)
VALUES (
'',
'".mysql_real_escape_string($item->title)."',
'".mysql_real_escape_string($item->description=htmlspecialchars(trim($item->description)))."',
'".mysql_real_escape_string($item->link)."',
'".mysql_real_escape_string($item->pubdate)."');
$selres = mysql_query($selsql);
$insRes = mysql_query($insSQL);
Don't use single quote around column names, if anything use ` to wrap column names. You also didn't have quotes around your $selSQL, see below and try it:
$selSQL = "SELECT * FROM `rss-feeds` ORDER BY `title`";
$insSQL = "INSERT INTO `rss_feeds` (`id`, `title`, `description`, `link`, `pubdate`)
VALUES (
'',
'".mysql_real_escape_string($item->title)."',
'".mysql_real_escape_string($item->description=htmlspecialchars(trim($item->description)))."',
'".mysql_real_escape_string($item->link)."',
'".mysql_real_escape_string($item->pubdate)."')";
$selres = mysql_query($selsql);
$insRes = mysql_query($insSQL);