How to manage duplicate sql values that has to be unique? - sql

Users of my site can submit post title and post content by form. The post title will be saved and converted to SEO friendly mode (eg: "title 12 $" -> "title-12"). this will be this post's url.
My question is if a user entered a title that is identical to previous entered title, the url's of those posts will be identical. So can be the new title be modified automatically by appending a number to the end of the title?
eg:
"title-new" -> "title-new-1" or if "title-new-1" present in db
convert it to "title-new-2"
I'm sorry I'm new to this, maybe it's very easy, Thanks for your help.
I'm using PDO.

when saving the post title you can query the db if it exists? If it exists the simply append a number and again query, if it again exists increment it by one and hence.

Do a select on your database for that title, and use rowCount() to check how many results you have. If the result is 0: you can add it, if the result is n, you add n to the title.
To append use something like this (not correct):
$count = $del->rowCount(); //Assuming this returns 1
if($count){
$title = $title . "-" . $count;
}
This will give you "theduplicatetitle-1"

thank you #Ratna & #Borniet for your answers. i'm posting explained code to any other user who want's it. if there is somrthing should be added or removed or better way please let me know.
//first i'm going to search the "new unchanged title name" whether it's present in db.
$newtitle= "tst-title";
$dbh = new PDO("mysql:host=localhost;dbname='dbname', 'usrname', 'password');
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `col.name` = ? LIMIT 1");
$stmt->execute(array($newtitle));
if ( $stmt->rowCount() < 1 ) {
// enter sql command to insert data
}
else {
$i='0';
do{
$i++;
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `url` = ? LIMIT 1");
$stmt->execute(array($newtitle.'-'.$i));
}
while($stmt->rowCount()>0);
// enter sql command to insert data
}
that's it. the reason i'm dividing in to two is because i want to add '-' to the url instead of just number.

Related

SQL Redshift - count number of times column A value appears in column B value [duplicate]

I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;
select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049
You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.

TYPO3 $query->in('valOne,valTwo,valThree', $arrayTwo)

I have a query in my repository which gets all product by categories and contentTypes.
I am looking for a query like this:
$query = $this->createQuery();
$constraint = $query->in('category', $categories);
if (!empty($contentType)) {
$results = $query->matching(
$query->logicalAnd(
$constraint, $query->in('contentType', $contentType)
)
)
->setLimit((int)$limit)
->setOffset((int)$offset)
->execute()
->toArray();
It works well if 'containType' contains just a single id as string, e.g '261'.
But if it is a string with multiple id's it looks like '261,284,291' and the query does not work longer.
I hope you got all information. Let me know if not :)
You can use GeneralUtility::trimExplode() or in your case probably more specific GeneralUtility::intExplode() to turn the $contentType CSV value into an array of values suitable for QueryInterface::in().

How to retrieve data from 2 column in one table?

I have a table named accessories_other in my database. In the table, I have column :
1) Item
2)Available
This is the illustration on how the data in the respective column.
Item
Mouse
Keyboard
Cable
Available
4
6
3
The thing is, I would like to select Item = 'Mouse' together with column 'Available'=4. If the available mouse is less than 5, it will send me an email for the next step. But I stuck until this stage.
This is SQL statement that I create, and it count each row for 'Available' column, and send the email if the row of Available column is less than 5, which is not I want.
$sql ="SELECT Item, Available FROM accessories_other WHERE Item ='Mouse'
AND Available <5";
How do I do so that it can retrieve mouse which is the availability less than 5.
This is just to show how it could be done . You should be using MySQLi
or PDO . Also if in Production environment , you should not be
displaying MySQL errors to the user .
You could do it either way :
// SQL to find Available value for Item Mouse
$sql = "SELECT Item, Available FROM accessories_other
WHERE Item = 'Mouse'";
$result = mysql_query( $sql ) or die( 'Query failed.'.mysql_error() );
$row = mysql_fetch_array( $result ) ;
if( mysql_num_rows( $result ) > 0 )
{
echo $row['Item'] ,': ' ,$row['Available'];
if( $row['Available'] < 5 )
{
// Code to send email
}
else
{
// Code to what ever you would like to do here
}
}
or
// SQL to find Available value for Item Mouse if it is less than 5
$sql = "SELECT Item, Available FROM accessories_other
WHERE Item = 'Mouse' AND Available < 5";
$result = mysql_query( $sql ) or die( 'Query failed.'.mysql_error() );
if( mysql_num_rows( $result ) > 0 )
{
// Code to what ever you would like to do here
}
else
{
echo $row['Item'] ,': ' ,$row['Available'];
// Code to send email
}
I think your query will not show results of mouse which is lesser than 5..
I suggest you try:
$sql ="SELECT Item, Available FROM accessories_other WHERE Item ='Mouse';
and then, try to implement your code in another language..
if I'm not mistaken, you're using php..
your query should return exactly one row if you have data in table "accessories" as shown here. unless you have duplicates like multiple rows rows with Item = 'Mouse' and same or different value which is also less than 5 then only query will return multiple results.
also just notice that in the explanation you use the table "accessories" but in sample query you have used table "accessories_other". make sure you are working against the right table.

PHP values inside pdo->query or/and prepared statements

I'm limiting the amount of comments shown on the page by 2, $second_count counts how many posts are if more than 2 it limits and show's a Show All comments, that's what this is for.
If you look into the variable $limitPost, how do I add parameter inside it.
This is what I'm trying to accomplish but with PDO.
$limitPost = "DESC LIMIT $second_count,2"; but this can lead to SQL INJECTIONS to my understanding.
PUBLIC FUNCTION userComments($post_iD,$second_count)
{
$limitPost = "DESC LIMIT 2";
$sth = $this->db->prepare("SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username, U.photo
FROM comments C, users U
WHERE U.status='1' AND C.uid_fk = U.uiD
AND C.msg_id_fk = :postiD
ORDER BY C.com_id < :second_count");
$sth->bindParam(':postiD', $post_iD, PDO::PARAM_INT);
$sth->bindParam(':second_count', $limitPost, PDO::PARAM_INT);
$sth->execute();
$data = $sth->fetchAll();
return $data;
}
UPDATE
This is what $second_count is, it it's just counting if there are 2 comments showing, it'll hide all the rest and if I press show all comments it'll expand.
<?php
$x=1;
if($x){
$comment_count = count($commentsarray);
$second_count = $comment_count-2;
if($comment_count>2){
?>
<div class="comment_ui" id="view<?php echo $post_iD;?>">
Show all <?php echo $comment_count;?> comments
</div>
<?php
$commentsarray = $Wall->userComments($post_iD, $second_count);
}
}
?>
alright:
If you look into the variable $limitPost, how do I add another
variable inside it.
This is what I'm trying to accomplish but with PDO.
impossible <- that is the answer to your question
instead of :
:second_count
try:
DESC LIMIT 2
into the prepared statement. You really do not need the parameter :second_count in your prepared statement since it is a constant string.
SQL injections would be possible if :second_count was an input by a user, since is it constant, nothing like that is possible.
Why what you are doing is not working:
DESC LIMIT 2 is not an integer parameter, so the bind should fail or give out junk.
If you were to use PDO::PARAM_STR on the bind, :second_count would be put into qoutes, so the sql statement would fail.

SELECT MAX query returns only 1 variable + codeigniter

I use codeigniter and have an issue about SELECT MAX ... I couldnot find any solution at google search...
it looks like it returns only id :/ it's giving error for other columns of table :/
Appreciate helps, thanks!
Model:
function get_default()
{
$this->db->select_max('id');
$query = $this->db->getwhere('gallery', array('cat' => "1"));
if($query->num_rows() > 0) {
return $query->row_array(); //return the row as an associative array
}
}
Controller:
$default_img = $this->blabla_model->get_default();
$data['default_id'] = $default_img['id']; // it returns this
$data['default_name'] = $default_img['gname']; // it gives error for gname although it is at table
To achieve your goal, your desire SQL can look something like:
SELECT *
FROM gallery
WHERE cat = '1'
ORDER BY id
LIMIT 1
And to utilise CodeIgniter database class:
$this->db->select('*');
$this->db->where('cat', '1');
$this->db->order_by('id', 'DESC');
$this->db->limit(1);
$query = $this->db->get('gallery');
That is correct: select_max returns only the value, and no other column. From the specs:
$this->db->select_max('age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as age FROM members
You may want to read the value first, and run another query.
For an id, you can also use $id = $this->db->insert_id();
See also: http://www.hostfree.com/user_guide/database/active_record.html#select
CodeIgniter will select * if nothing else is selected. By setting select_max() you are populating the select property and therefore saying you ONLY want that value.
To solve this, just combine select_max() and select():
$this->db->select('somefield, another_field');
$this->db->select_max('age');
or even:
$this->db->select('sometable.*', FALSE);
$this->db->select_max('age');
Should do the trick.
It should be noted that you may of course also utilize your own "custom" sql statements in CodeIgniter, you're not limited to the active record sql functions you've outlined thus far. Another active record function that CodeIgniter provides is $this->db->query(); Which allows you to submit your own SQL queries (including variables) like so:
function foo_bar()
{
$cat = 1;
$limit = 1;
$sql = "
SELECT *
FROM gallery
WHERE cat = $cat
ORDER BY id
LIMIT $limit
";
$data['query'] = $this->db->query($sql);
return $data['query'];
}
Recently I have been utilizing this quite a bit as I've been doing some queries that are difficult (if not annoying or impossible) to pull off with CI's explicit active record functions.
I realize you may know this already, just thought it would help to include for posterity.
2 helpful links are:
http://codeigniter.com/user_guide/database/results.html
http://codeigniter.com/user_guide/database/examples.html