Hey, what's the most effective way to remove beginning and ending slashes from all rows in a particular column using MySQL?
Before:
/hello/world/
foo/bar/
/something/else
/one/more/*
After:
hello/world
foo/bar
something/else
one/more/*
...or maybe this should be done in PHP instead?
See TRIM()
UPDATE MY_TABLE SET my_field=TRIM(BOTH '/' FROM my_field);
You could definitelyt make this work using the MySQL string functions but I think this would be best handled outside of the database using PHP or whatever programming language of your choice.
Your PHP option: (I'm assuming the fetched row is in $row)
$row['Field'] = explode('/', $row['Field']);
//Remove the empty elements
$row['Field'] = array_filter($row['Field']);
$row['Field'] = implode('/', $row['Field']);
Related
I have a column within my database that holds text similar to this
CNEWS # Trinidad : "By Any Means Necessary" Watson Duke Swims And Sails To Toco http://somewebsitehere.com
What can I do to remove the entire http address from the column? Please note that some links may be broken so it may have http:// somewebsitehere.com
I was thinking of using a substring index but not sure that would work.
You could use whichever your favorite programming language is to iterate through the rows in the table, pluck out that column, apply a regular expression replacement rule to it, then update the row in the table with the new value.
Here is some pseudo-code:
theRows = SELECT * FROM TheTable WHERE 1;
foreach row in theRows
BEGIN
oldColumnValue = row[theColumnName]
// Removes any link appearing at the end of the column
newColumnValue = oldColumnValue.replace(/http:\/\/[^\s]*$/, '')
UPDATE TheTable SET theColumnName = newColumnValue WHERE id = row[id]
END
For something as small and specific as this, you could use perl with the DBI library to connect to mySQL. Here's a useful resource on regular expressions if you want to go more into it: http://www.regular-expressions.info/perl.html
I have a problem with the way of escape of Query Builder in Codeigniter 3.0.
For example, this code
echo $this->db->select('ROUND(3.456, 1) AS T1')->get_compiled_select();
Return:
SELECT ROUND(3.456, `1)` AS `T1`
The function put backticks after a coma, but this is solved by setting FALSE the second parameter. But the function "from" put always backticks:
echo $this->nm->db->from('(SELECT ROUND(3.456, 1)) AS T1')->get_compiled_select()
Return:
SELECT * FROM (SELECT ROUND(3.456, `1))` AS `T1`
I'm using Codeigniter 3.0. The problem exists since Codeigniter 2.2. I need use the Query Builder beacuse it's very easy to use, but its escape method is troublesome. How stop the escaping in the function from?
Thanks.
I found a solution, but I'm not sure use it. In "database.php" file should be added a new element for the config array of database connection.
$db['default']['_protect_identifiers'] = FALSE;
That code disable the escape mode. But is it advisable? What is the risk of disabling the escaping system?
Thanks.
or you can disable on current query and enable it again rather on whole app. Before query, insert
$this->db->_protect_identifiers = FALSE;
and after query, set to TRUE to enable it again.
I have the following sql statement written in PHP.
$sql='INSERT INTO pictures (`picture`) VALUES ("'.$imgs[$i]['name'].'",)';
$db->query($sql);
$imgs[$i]['sqlID'] = $this->id=mysql_insert_id();
$imgs[$i]['newImgName'] = $imgs[$i]['sqlID'].'_'.$imgs[$i]['name'];
$sql='UPDATE pictures SET picture="'.$imgs[$i]['newImgName'].'" WHERE id='.$imgs[$i]['sqlID'];
$db->query($sql);
Now this writes the image name to database table pictures. After that is done I get the mysql_insert_id() and than I'll update the picture name with the last id in front of the name with underscore.
I'll do this to make sure no picture name can be the same. Cause all those pictures get saved in the same folder. Is there another way to save that ID already the first time I set the sql query? Or are there other better ways to achieve this result?
Thanks for all advices
Using the native auto_increment - there is no other way. You need to do the 3 steps you described.
As Dan Bracuk mentioned, you can create a stored proc to do the 3 queries (you can still get the insert id after executing it).
Other possible options are:
not storing the id in the filename - you can concatenate it later if you want (when selecting)
using an ad-hoc auto increment instead of the native one - I would not recommend it in this case, but it's possible
using some sort of UUID instead of auto increment
generating unique file names using the file system (Marcell Fülöp's answer)
I don't think in this particular case it's reasonable to use MySQL insert Id in the file name. It might be required in some cases but you provided no information why it would be in this one.
Consider something like:
while( file_exists( $folder . $filename ) {
$filename = rand(1,999) . '_' . $filename;
}
$imgs[$i]['newImgName'] = $filename;
Of course you can use a larger range for rand or a loop counter if you wanted tot systematically increment the number used to prefix the original file name.
1st I'll give you the query, and then I'll tell you what I am trying to achieve, as I could be soo wrong or soo close.
mysql_query("UPDATE link_building SET
ID=$ID,Site=$Site,Date=$Date,Target_Site=$Target_Site,
Target_Contact_Email=$Target_Contact_Email,
Target_Contact_Name=$Target_Contact_Name,
Link_Type=$Link_Type,Link_Acquired=$Link_Acquired,
Notes=$Notes,Link_URL=$Link_URL WHERE ID=" . $ID);
What am I trying to achieve?
I want to update the fields
("ID","Site","Date","Target_Site","Target_Contact_Email","Target_Contact_Name",
"Link_Type","Link_Acquired","Notes","Link_URL")
in the table link_building with the values stored in the variables
("$ID","$Site","$Date","$Target_Site","$Target_Contact_Email","$Target_Contact_Name",
"$Link_Type","$Link_Acquired","$Notes","$Link_URL")
But I only want to update the record whos Id is equal to $ID.
UPDATE: I DO NOT SEE ANY ERROR. ITS REDIRECTS TO link_building.php and displays success message but doesn't change the data in the MySQL table.
Try escaping the data and removing the update of the ID since its already in your conditions:
mysql_query("UPDATE link_building SET Site='".mysql_real_escape_string($Site)."',Date='".mysql_real_escape_string($Date)."',Target_Site='".mysql_real_escape_string($Target_Site)."', Target_Contact_Email='".mysql_real_escape_string($Target_Contact_Email)."', Target_Contact_Name='".mysql_real_escape_string($Target_Contact_Name)."', Link_Type='".mysql_real_escape_string($Link_Type)."',Link_Acquired='".mysql_real_escape_string($Link_Acquired)."', Notes='".mysql_real_escape_string($Notes)."',Link_URL='".mysql_real_escape_string($Link_URL)."' WHERE ID=" . intval($ID));
For one, you're forgetting that you still need to quote your strings;
mysql_query("UPDATE link_building SET Site='$Site', Date='$Date',".
"Target_Site='$Target_Site', Target_Contact_Email='$Target_Contact_Email',".
"Target_Contact_Name='$Target_Contact_Name', Link_Type='$Link_Type',".
"Link_Acquired='$Link_Acquired', Notes='$Notes', Link_URL='$Link_URL' ".
"WHERE ID=$ID");
Note the added 's around all strings.
Bonus remark; you should really be using mysql_real_escape_string() on your strings before passing them on to the database.
if your columns are named like Target Site (with a space in it), you should adress it like that in your query (wich will force you to add backticks to it). also, you'll have to add quotes to colums that store anything else that strings. your query should look like:
UPDATE
link_building
SET
ID = $ID,
Site = '$Site', // single quotes for values
Date = '$Date', // ...
´Target Site´ = '$Target_Site' // and ´ for fields
[...]
this should solve why the query doesn't work (in addition: not how a bit or formatting makes it much more readable).
you havn't given information about that, but please note that you should always sanitize your variables before using it (your code doesn't look like you do) to avoid sql-injections. you can do this using mysql_real_escape_string or, even better, start using prepared statements.
I have couple of mysql queries in perl but some of the values of the where clause contain space between words e.g. the gambia. When my scripts runs with the where clause arguments containing a space it ignore the second word.
I want to know how can I solve this problem i.e. if I type the gambia it should be treated the gambia not the.
If you are using DBI, you can use placeholders to send arbitrary data to database without need to care about escaping. The placeholder is question mark in prepare statement, actual value is given to execute:
use DBI;
$dbh = DBI->connect("DBI:mysql:....",$user,$pass)
or die("Connect error: $DBI::errstr");
my $sth = $dbh->prepare(qq{ SELECT something FROM table WHERE name = ? });
$sth->execute('the gambia');
# fetch data from $sth
$dbh->disconnect();
Edit: If you are composing the query (as you suggested in comments), you can utilize quote method:
my $country = "AND country = " . $dbh->quote('the gambia');
my $sth = $dbh->prepare(qq{ SELECT something FROM table WHERE name = ? $country});
Well, firstly, you should look at using something like DBIx::Class instead of raw SQL in your application.
But if you're stuck with raw SQL, then (assuming that you're, at least, using DBI) you should use bind points in your SQL statements. This will handle all of your quoting problems for you.
$sth = $dbh->prepare('select something from somewhere where country = ?');
$sth->execute('The Gambia');
See the DBI docs for more information about binding.