Thursday, 29 March 2018

sql - When to use single quotes, double quotes, and backticks in MySQL



I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.




Example:



$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';


Also, in the above example, consider that table, col1, val1, etc. may be variables.



What is the standard for this? What do you do?




I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.


Answer



Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.



Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.



MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.



So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.




None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).



Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.



Backtick (`)
table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`)
VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())
";
↑↑↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑↑↑↑↑

Unquoted keyword ─────┴┴┴┘ │ │ │ │ │ │ │││││
Single-quoted (') strings ───────────┴────┴──┴────┘ │ │ │││││
Single-quoted (') DATE ───────────────────────────┴──────────┘ │││││
Unquoted function ─────────────────────────────────────────┴┴┴┴┘


Variable interpolation



The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).




// Same thing with some variable replacements
// Here, a variable table name $table is backtick-quoted, and variables
// in the VALUES list are single-quoted
$query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";


Prepared statements



When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:




// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";

// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";


Characters requring backtick quoting in identifiers:



According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:





ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)




You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.


javascript - JSON to Initialize Data in Service

I'm developing a small AngularJS app and I'm currently struggling with creating a service.


I have a service that serves as a backend for providing contacts (name, address...).
Until now they were hard-coded as an array in the service (instance.contacts=[...]), but now I'm trying to read them from a json file :


myModule.factory('contactService', ['$http',function ($http) {
var instance = {};
$http.get('contacts.json').success(function (data) {
instance.contacts = data;
});
return instance;
}]);

I see in my browser console that the file has been read successfully, but I don't see any change on-screen.


So I tried the following instead, and it worked :


myModule.factory('contactService', ['$http',function ($http) {
var instance = {
contacts:[]
};
$http.get('contacts.json').success(function (data) {
angular.forEach(data, function(item) {
instance.contacts.push(item);
});
});
return instance;
}]);

I don't know why the second code snippet works, and not the first. Could someone please help me understand ?

'horror' tag wiki - Movies & TV



A genre of fiction in which events are focused on shocking or scaring the viewer by inducing feelings of terror or horror. Use this tag when asking questions pertaining to the overall genre of horror.




Horror fiction is a broad genre of fiction that is designed to scare or shock the viewer. Such movies or shows include events that induce feelings of fear or terror in the viewer.




The horror genre includes a number of more specific sub-genres, though most horror films tend to mix elements from different sub-genres. Some of the more popular are:




  • Psychological Thriller - relies more heavily on subtle or implied terror, sound effects, and hidden/unseen antagonises; Rosemary's Baby, The Shining

  • Slasher - Focuses on a single or small number of serial killers that commit multiple violent and gory murders on screen. Frequently includes elements of the supernatural - Friday 13th, Nightmare on Elm Street, Halloween

  • Gothic Horror - One of the oldest types of horror, frequently includes a romance as a core plot-line; Dracula, Sleepy Hollow, Nosferatu

  • Splatter - Includes scenes of extreme or excessive violence and gore; Saw, Hostel

  • Zombie Horror - Depicts a world being taken over by zombies; Dawn of the Dead, 28 Days Later




Horror films frequently include several tropes that are unique to the genre; the presence of these tropes is often a defining characteristic of a horror film.

vba - Close excel application using Powershell



I am initiating a macro in a workbook from powershell (to automate a process). The below in powershell opens the excel workbook and runs the macro without visualizing the process.



The issue is even though I do not see the macro running, the new instance of excel generated from the macro is still open.



# start Excel
$excel = New-Object -comobject Excel.Application

#open file
$FilePath = 'C:\file\Book1.xlsm'
$workbook = $excel.Workbooks.Open($FilePath)


#access the Application object and run a macro
$app = $excel.Application
$app.Run("macro")


#close excel
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Start-Sleep 1
'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count
Remove-Variable $excel

exit $LASTEXITCODE


The excel file still comes up as a process in task manager and is taking up memory space.



How do I have powershell completely close the instance of the excel application that opens through the macro?



enter image description here



Any help greatly appreciated!


Answer



Try using Quit method before you release COM object, like this:



$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel

javascript - What does (function($) {})(jQuery); mean?

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.



1. (
2. function(){}
3. )
4. ()



Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help



1. function(){ .. }
2. (1)
3. 2()


You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.



An example of how it would be used.




(function(doc){

doc.location = '/';

})(document);//This is passed into the function above


As for the other questions about the plugins:




Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.



Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.



Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

javascript - remove object from js array knowing it's Id




I have array of object inside razor view (javascript code).



var myArr;



on page load contains let's say 10 objects.



one object has following structure



 - Id  
- Name



how can I remove object from js array knowing it's Id?


Answer



Try like this



var id = 2;
var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,

Name: 'b'
}, {
Id: 3,
Name: 'c'
}];
var index = list.map(x => {
return x.Id;
}).indexOf(id);

list.splice(index, 1);

console.log(list);


JSFIDDLE



Or you can utilize .filter()



Like this



var id = 2;

var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,
Name: 'b'
}, {
Id: 3,
Name: 'c'
}];

var lists = list.filter(x => {
return x.Id != id;
})
console.log(lists);


DEMO


javascript - Update a div with jQuery

I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:




page.html:















If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:



http://37.187.90.121:3874/currentsong?sid=1&c=


The output of this source is like this:





Inna - Un Momento



If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?



EDIT1:
ok is a policy problem, how i can resolve it?




EDIT2:+
The proxy php page solution don't work.
I have make this php page:



echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>


But i have this error message:




Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2

Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2


Edit3:
The external service give me a javascript to get the information:



window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('Unavailable'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++


You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js



Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.



This script give me an output like:





"Radio Name - Author - Title of song"




and this is a link (if you click on it open another page).



I need to get only "Author - Title of song" with no link. Any idea?



Edit4:



I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:













sss




casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...