sort a field in my table in MySQL - mysql

I have a set of data like this:
ID | Name | Code
1 | John | ygkj
2 | Mike | ghyy
3 | Jay | uuja
And I want to use a function/stored procedure to change the "Code" column into the following:
ID | Name | Code
1 | John | gjky
2 | Mike | ghyy
3 | Jay | ajuu
Or maybe throwing it as a result of a SELECT statement. How can I do it with MySQL?
Thanks!!

Finally, I've done it via PHP. If anyone needs it, I'll post my script here
$inorder = array();
$result = $mysqli->query("select ID, Code from top");
while ($line = $result->fetch_assoc()) {
$stringParts = $line['Code'])
sort(str_split($stringParts);
$inorder[$line['ID']] = implode('',$stringParts);
}
foreach($inorder as $k=>$l)
{
$mysqli->query("update codes SET Code = '".$l."' where id_top = ".$k);
}
It seems like MySQL doesn't have complex array operations to work with the data within the results.

Related

How to add incremental values to mysql database after sorting entries

ID | LastName | FirstName | Ordered
1 | Smith | John |
2 | Smith | Larry |
3 | Jones | Fred |
4 | Johnson | Todd |
Desired result: Update the Ordered field with incremental values in alphabetical order.
1 | Smith | John | 3
2 | Smith | Larry | 4
3 | Jones | Fred | 2
4 | Johnson | Todd | 1
$result = mysql_query("SELECT * FROM MyDatabase ORDER by
LastName,FirstName");
$N=0;
while ($row = mysql_fetch_array( $result ))
{
mysql_query("
UPDATE MyDatabase
SET Ordered = $N + 1
WHERE ...");
}
I know I need the WHERE but I can't seem to make any WHERE clauses work. I always end up with all the same numbers in the Ordered field. What would make this work as intended?
Sounds like you first need to get a total count of all rows in the result set (since you're storing from high to low you need to know the high). Then just decrement that value during the UPDATE / loop
Well, I figured this out to make it work. Just need to fetch the row and then compare it to the ID field as follows:
$result = mysql_query("SELECT * FROM MyDatabase ORDER by LastName, FirstName");
$N=1;
while ($row = mysql_fetch_array( $result ))
{
$updateid = $row['ID'];
mysql_query("
UPDATE MyDatabase
SET Ordered = $N
WHERE ID='$updateid'");
$N++;
}

how to tokenize string in record to be row

I have the data in a database table named term like this :
---------------------------------------
id_term | keyword |
------- | -----------------------------
1 | how to make search engine |
2 | application engineering |
3 | android application example |
--------------------------------------
then I want it to be like this table :
----------------------------------
| id_term | keyword |
----------------------------------
1 | how |
1 | to |
1 | Make |
1 | search |
1 | engine |
2 | application |
2 | engineering |
3 | example |
3 | application |
3 | android |
----------------------------------
I've tried googling to find references to split the string, but still have not found the appropriate expectations. In an experiment that I've done using substring_index results I could actually like this:
---------------------------------------
id_term | keyword |
------- | -------------------------------
1 | how to make search engine |
1 | how to make search engine |
1 | how to make search engine |
--------------------------------------
there anything you can help me or has the solution of my problem? mysql code that I try something like this:
select term.id_kata, SUBSTRING_INDEX (SUBSTRING_INDEX (term.keyword, ',', term.id_kata), ',', -1) keyword term from inner join keyword_doc on CHAR_LENGTH (term.keyword) -CHAR_LENGTH (REPLACE (term.keyword , ',', ''))> = term.id_kata-1 ORDER BY `term`.`keyword` DESC
I've tried googling for approximately 5 hours to find a solution, but have not found until I was confused to be asked where. there any ideas or can help provide a solution?
The solution for it problem is please take 'BETWEEN' in SQL SYNTAX. this code 100% work for it problem :
<?php
#connection
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pasword';
$dbname = 'yourdatabasename';
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect($dbhost,$dbuser,$dbpass) or die(mysqli_error('cannot connect to the server'));
mysql_select_db($dbname) or die(mysqli('database selection problem'));
$frequency = array();
$datastring = 'SELECT id_term,keyword FROM data_token WHERE id_term BETWEEN 1 AND 3';
mysql_select_db('yourdatabasename');
$calldata = mysql_query($datastring);
while($takedata = mysql_fetch_array($calldata,MYSQL_ASSOC))
{
$array = explode("\n",$takedata['keyword']);
foreach ($array as $index => $keyword)
{
if(! array_key_exists($keyword,$frequency))
{
$frequency[$keyword] = 1;
}
else
{
$frequency[$keyword] = $frequency[$keyword] + 1;
}
}
$document = $takedata['id_term'];
foreach ($frequency as $term => $tf)
{
$sqlInput = "INSERT INTO yourtablename (id_term,keyword,frequency) VALUES ('$dokumen','{$term}', {$tf})";
mysql_query($sqlInput);
}
}
?>

Missing an option to use SQL's HAVING clause in F3

Is there a way to use MySQL's HAVING clause with any of Fat Free Framework's SQL Mapper object's methods? Let's assume I have the following DB table:
+----+-------+--------+
| id | score | weight |
+----+-------+--------+
| 2 | 1 | 1 |
| 2 | 2 | 3 |
| 2 | 3 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 4 |
| 3 | 3 | 1 |
| 3 | 4 | 3 |
+----+-------+--------+
Now I would like to run a following query:
SELECT id, SUM(score*weight)/SUM(weight) AS weighted_score GROUP BY id HAVING weighted_score>2
Truth to be told I would actually like to count the number of these records, but a count method doesn't support $options.
I can run the query without a HAVING clause and then loop through them to check weighted_score against the value, but with a growing number of records will make it more and more resource consuming. Is there any built-in solution to solve this problem?
EDIT 1:
The way I know how to do it if there is no support for the HAVING clause (based on manual):
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$usersInfo = $dataMapper->find([],["group"=>"id"]);
$place = 1;
foreach ( $usersInfo as $userInfo ) {
if ( $usersScores->weightedScore > 2) $place++;
}
If I were able to use HAVING clause then the foreach loop would not be needed and the number of items loaded by a query would be reduced:
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$usersInfo = $dataMapper->find([],["group"=>"id", "having"=>"weighted_score<2"]); // rough idea
$place = count($usersInfo);
And if count method supported $options it would be even simpler and it would save memory used by the app as no records would be loaded:
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$place = $dataMapper->count([],["group"=>"id", "having"=>"weighted_score<2"]); // rough idea
Use Sub Query.
select count (0) from (SELECT id, SUM(score*weight)/SUM(weight) AS weighted_score GROUP BY id) where weighted_score>2;
Hope it will help.
As far as I know, you can put the HAVING clause into the group option:
$usersInfo = $dataMapper->find([],["group"=>"id HAVING weighted_score<2"]);
Another way could be to create a VIEW in mysql and filter the records on a virtual fields in that view.

mysql join one to many with images

I have two tables...
project table
+----+--------+
| id | client |
+----+--------+
| 1 | James |
| 2 | John |
+----+--------+
images table
+----+-----------+-------------------+
| id | projectId | imagePath |
+----+-----------+-------------------+
| 1 | 1 | images/image1.jpg |
| 2 | 1 | images/image2.jpg |
| 3 | 2 | images/image3.jpg |
| 4 | 2 | images/image4.jpg |
| 5 | 2 | images/image5.jpg |
+----+-----------+-------------------+
As you can see, one project has many images. I want to display that
this way...
James
images/img1.jpg
images/img2.jpg
John
images/img3.jpg
images/img4.jpg
images/img5.jpg
This post gave me what I want https://stackoverflow.com/a/2451065/1214535
But when I echo like so
<img src='".$row['imagePath']."/>
the results in image tag I get this
<img src="images/img3.jpg,images/img4.jpg,images/img5.jpg">
instead of
<img src="images/img3.jpg"/>
<img src="images/img4.jpg"/>
<img src="images/img5.jpg"/>
How can I change the query so that I can display the images properly/separately
this is the query I am using
$sql="SELECT images.projectId,project.client,
GROUP_CONCAT(images.imagePath SEPARATOR ', ')
AS 'imagePath'
from project left JOIN images on project.id=images.projectId
GROUP BY project.id ASC";
thank you guys...
You could try using foreach to loop through different values.
Syntax:
foreach (array_expression as $value)
statement
First insert all the values you get in an array like this:
$imgArray = explode(',',$row['imagePath']);
Then loop through this array as:
foreach ($imgArray as $img)
{
echo "<img src='$img'" />";
}
you have to break the string like below
$imgArray = explode(',',$row['imagePath']);
//then do
foreach($imgArray as $im)
{
if( is_readable($im) ) {
echo "<img src='$im' title='Image' />";
}
}
I believe that EXPLODE is the answer.Look at PHP explode - running loop through each array item Stack overflow question. I believe that it will answer to your question.
Also, I think (another approach) if you change ur query to
SELECT tp.CLIENT,ti.IMAGEPATH
FROM tblProject tp
JOIN tblImage ti ON tp.Id = ti.ProjectId
then a simple loop will be easy to get you through.
Because you are using GROUP_CONCAT which is returning all non-null values as string.
You can use below query:
$sql="SELECT images.projectId,project.client,images.imagePath SEPARATOR
AS 'imagePath'
from project left JOIN images on project.id=images.projectId
GROUP BY project.id ASC";
And loop through result.

MySQL Update query with Dynamic contenct

In MySQL, I have two tables:
CATEGORY
----------------------------------------------
| category_name | category_code |
----------------------------------------------
| Suit | SU |
| Western | WE |
----------------------------------------------
PRODUCT
---------------------------------------------
| name | Category | code |
---------------------------------------------
| xyz1 | Suit | |
| abc1 | Suit | |
| abc2 | Western | |
---------------------------------------------
I want to update code in PRODUCT, so that after updation it is will:
PRODUCT
---------------------------------------------
| name | Category | code |
---------------------------------------------
| xyz1 | Suit | SU/0001 |
| abc1 | Suit | SU/0002 |
| abc2 | Western | WE/0001 |
---------------------------------------------
thanks in advance
Honestly, it looks like you need restructure your database. Each table should have an auto-incrementing "id" field. This would allow the "Category" field to reference an id instead of a duplicate of the name (in case you EVER decide to change the spelling or name of that category). Even down to your naming - if your field is IN the category table, it doesn't seem necessary to have "category_" before the "code" field name...etc
Beyond that, you're probably talking about a PHP script (or something similar) - this would allow you to repeat through each item and keep track of how many Suit codes you've added so you can increment your "code" field (I assume that's what the 0001 0002 is doing.
Off the top of my head, it'd be something like this (I'm sure it could be more streamlined/better - but hopefully this gives an idea of a way you could do it:
$numSU = 0;
$numWE = 0;
$products = mysql_fetch_array(mysql_query("SELECT * FROM product"));
foreach($products as $p) {
$codeQuery = mysql_query("SELECT category_code FROM category WHERE category_name='".$p['Category']."'");
$code = mysql_result($codeQuery,0,'category_code');
if($code == "SU") {
$numSU++;
$numItems = $numSU;
} else if($code == "WE") {
$numWE++;
$numItems = $numWE;
}
$update = mysql_query("UPDATE product SET code='".$code."/".$numItems."'");
}