PHP and MySQL Basics II – Case Sense

Last time we set up a connection from a PHP program to a MySQL server. This time we will progress a little further in that direction.

Query

Data is asked for from the MySQL server by using a query written in a language named Structured Query Language (SQL). Now that we have a connection open to the server, we can pass out request to the server.

Manual Labor

The PHP Manual is wonderful 99% of time. If you take a peek at the page for mysqli::query there is a great example of a simple query. Many of learned to program by copying/pasting from books/manuals and this is a great us of the examples in the PHP manual. Except it may not work for you.

MySQL is usually case SeNsATiVe, so ‘A’ may not be the same thing as ‘a’. But this is dependent to some extent on your operating system where ‘A’ = ‘a’. I was using the example from the manual and … it did not work.

What Happened

Here is an excerpt of the code, somewhat cut down:


<?php
$mysqli = new mysqli("localhost", "user", "secret", "world_x");

/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

$mysqli->close();
?>

Run the program and … nothing.

So What Happened?

What happened is a subtle problem that novices will smack into very hard. Take a look at this section of the example.

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);

/* free result set */
$result->close();
}

If you try the query SELECT Name FROM City LIMIT 10; with the MySQL command line client program you will get the answer. And the answer is:

mysql> SELECT Name FROM City LIMIT 10;
ERROR 1146 (42S02): Table 'world_x.City' doesn't exist
mysql>

I am using the new world_x example database where the city is NOT capitalized instead of the old world database where it is! This lesson can be summed as check you schema/table/column names for case sensitivity. Except that there is another problem here.

In the real world occasional the database/table/column that you carefully double checked was spelled correctly and with the proper case sensitivity will go away. It may have been renamed, deleted, munged, or what have you. What is needed is a way to check to see if there was an error if the query can not run.

Lets change the code slightly:

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);

/* free result set */
$result->close();
} else {
printf("Query failed: %s\n", $mysqli->error);

}

Always Check for Return Codes

By simply adding about 40 characters, the reliability of the program shoots up immensely AND we get an exact answer if what went wrong.

Query failed: Table 'world_x.City' doesn't exist

Same error as when we tried by query by hand. But now our code can handle this issue. We could even try to catch the error, send a note via a message queue to the operations staff about the nature of the problem, and possible limp along until things are resolved. Or we could just call exit()

When you are offered a return code be sure to check it. Yes, it may be over kill in simple examples. But the payoff comes when things go bad and you are scrambling to find out eleven months from now why your program is suddenly not working.
via Planet MySQL
PHP and MySQL Basics II – Case Sense

Honest Princess Bride Trailer

Honest Princess Bride Trailer

Link

Screen Junkies digs 30 years into the vaults to pay tribute to one of our all-time favorites. It’s got adventure, dark humor, romance, and a wealth of memorable characters and lines we still quote to this day. Also, we felt exactly like Fred Savage as the story unfolded.

via The Awesomer
Honest Princess Bride Trailer

PHP and MySQL Basics

PHP and MySQL have had a long intertwined path together. I have been talking with a lot of newbies in the past several months who are trying to become PHP developers but are amazed at all the ancillary parts that go along with PHP such as unit testing, databases, JavaScript, continuous integration, and much more. Add in that there are two MySQL APIs — PDO & MySQLi — and an older deprecated mysql API still often found in the wild. This blog is the start of a series for new PHP developers to learn to program with a database.

Client Server Model

The PHP code when it seeks to talk to a MySQL (or most other databases) will make a connection to a port at an IP address. Usually MySQL is listening on port 3306. If you are developing an accessing a database on your local computer the IP address used will generally be at 127.0.0.1. The software that goes between the PHP application and the database is called a connector.

So your code on you local system an be talking to a database server on your local system or through a network connection. It does not matter which.

Can’t connect to MySQL server on ‘x.x.x.x’ (111)

The Can’t connect error can be especially frustrating. An experienced developer will know what to check from tears of experience. But this is a column on basics so we need to spell out the steps.

  1. Is the IP address correct? It is easy to fat finger IP address and ironically 127.0.01 on many Linux boxes will connect up to 127.0.0.1.
  2. Is there a instance of MySQL running at that IP address?
  3. Is that instance listening on the generic port 3306? Is may be running someplace else and you will have to chance down that port number.
  4. Can the MySQL command line shell or other tool connect to the instance? MySQL Workbench, PhPMyAdmin, the cli tools, and everything else authenticate through the same steps so if they work and your PHP program does not then most likely the fault is in the PHP code.

Setting up the client server connection

The PHP Manual is worth its weight in gold and you should refer to it often. Its examples are clear, or usually as clear as can be, and concise. Below is an excerpt example from the manual.


<?php

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";
?>

Note that the IP address, user name of "user", password of "password", and the port of 3306 will need to be changed to fit the installation. The mysqli call sets up the connection between the application and the MySQL database server.

Please note that you should protect usernames and password or any other information that could allow someone to compromise the server and data.

The if statement is invoked when there is an error code is returned from the $mysql->connect_errono call. Subsequently the error message from the server can be printed out using $mysqli->error. The error message itself can be terse but often points out what is wrong in the code.

Bad arguments

What follows below are three bad connection strings.

// Bad IP address
$mysqli = new mysqli("19.10.0.3", "root", "barfoo", "world_x", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

// Bad account information
$mysqli = new mysqli("127.0.0.1", "root", "foobar", "world_x", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

// Bad database specified
$mysqli = new mysqli("127.0.0.1", "root", "foobar", "world_xx\", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

Part of mastering any computer programming language is learning to understand the error messages. The three examples above return similar but distinctly different messages.

The first of the trip provides the following error:


PHP Warning: mysqli::__construct(): (HY000/2002): Network is unreachable in /home/dstokes/php/m02.php
Failed to connect to MySQL: (2002) Network is unreachable

It would be nice to get more information than ‘Network in unreachable’ but it provides a starting point to diagnose the problem. Generally the more specific the problem, the more specific the error message.

The third of the trio attempts to connect to a database named ‘world_xx’ when we really wanted ‘world_x’.

PHP Warning: mysqli::__construct(): (HY000/1049): Unknown database 'world_xx' in /home/dstokes/php/m02.php
Failed to connect to MySQL: (1049) Unknown database 'world_xx'

Sadly for beginners it takes time and experience to get to the point where you can instantly look at an error and know what has gone wrong (or have a pretty good idea of what has gone wrong). But do not worry as many of us learn by correcting OUR mistakes and learning not to repeat them.

Connection Good

So after establishing a good connection to the MySQL server, we can now query it for data.

Next Time — what happened to my query??

via Planet MySQL
PHP and MySQL Basics

Cinder Speakers

Cinder Speakers

Link

Designer Daniel Ballou and Dashdot are working on this cool DIY audio system which lets you take ordinary cinder blocks and turn them into speakers. Apparently, the concrete minimizes vibration and coloration of sound. Ballou hopes to retail the kit for about $150.

via The Awesomer
Cinder Speakers

The Best 6 Sites to Get Free Ebooks

Book lovers all over the world are starting to wake up and smell the coffee: ebooks are way better than paper books


Books Suck: Why I Love My Kindle More Than Dead Trees




Books Suck: Why I Love My Kindle More Than Dead Trees

Modern e-readers hold thousands of novels, weigh next to nothing, have built in lights, and don’t give you a concussion when they hit your nose.
Read More

. The benefits are many, like not having to lug around a 10-pound doorstop, being able to bring your whole library with you everywhere, and backing up your entire library to the cloud.

But if you’re a voracious reader, buying ebook after ebook can burn a huge hole in your wallet. One option is to subscribe to an ebook subscription service


Scribd vs. Kindle Unlimited: Which Netflix for Books Is Best?




Scribd vs. Kindle Unlimited: Which Netflix for Books Is Best?

There are slim pickings for those who want an all-you-can-eat service for eBooks, with Scribd and Kindle Unlimited the only two offerings left. So, which deserves your hard-earned cash?
Read More

that grants access to an entire library of ebooks for a monthly membership of just a few dollars.

The other option is to save your money and switch to freely available ebooks instead. You’d be surprised how many ebooks you can get without paying a cent, and that applies to both fiction and non-fiction. Where can you find these free ebooks? Well, we’re glad you asked…

free-ebooks-site-bookzz

When BookZZ claims to be “the world’s largest ebook library,” it’s not kidding. It currently plays host to over 2.7 million ebooks as well as 52.4 million scientific articles from publications all over the world — it would take several lifetimes to consume everything on offer.

BookZZ has both fiction and non-fiction, spanning different genres (e.g. science fiction, fantasy, thrillers, romance) and types (e.g. novels, comics, essays, textbooks). It’s nothing short of impressive.

The books can be browsed in two ways: by category (of which there are 27 major categories and hundreds of minor categories) or by recently added (which isn’t terribly useful in my experience). The browsing interface is a bit messy, but it gets the job done.

Or you can use the search option, which lets you search by title, author, description, and more. The Advanced Search lets you narrow the results by year, language, and format (e.g. PDF, EPUB, MOBI, DOC). You’ll never run out of things to read here.

BookZZ is actually a mirror for LibGen, or Library Genesis, but we prefer BookZZ because its interface is less clunky and a bit easier to navigate.

free-ebooks-site-project-gutenberg

Project Gutenberg is a charity endeavor, sustained through volunteers and fundraisers, that aims to collect and provide as many high-quality ebooks as possible. Most of its library consists of public domain titles, but it has other stuff too if you’re willing to look around.

As of this writing, Gutenberg has over 53,000 free ebooks on offer. They are available for download in EPUB and MOBI formats (some are only available in one of the two) or they can be read online in HTML format.

You can browse the library by category (of which there are hundreds), by most popular (which means total download count), by latest (which means date of upload), or by random (which is a great way to find new material to read).

Because it’s a charity, Gutenberg subsists on donations. If you appreciate what they’re doing, please consider making a tax-deductible donation by PayPal, Flattr, check, or money order.

free-ebooks-site-feedbooks

Feedbooks is a massive collection of downloadable ebooks, both fiction and non-fiction, both public domain and copyrighted, both free and paid. As of this writing, over 1 million titles are available, but only a portion of them are free.

The split between “free public domain ebooks” and “free original ebooks” is surprisingly even. A big chunk of the public domain titles are short stories whereas a big chunk of the original titles are fanfiction, but don’t let that turn you away — you can find some great stuff here otherwise.

Most of the ebooks are available in EPUB, MOBI, and PDF formats. They even come with word counts and reading time estimates, in case you take that into consideration when choosing what to read.

free-ebooks-site-manybooks

ManyBooks is a nifty little site that’s been around for over a decade. Its purpose is to curate and provide a library of free and discounted fiction ebooks for people to download and enjoy.

Much of its collection was seeded by Project Gutenberg back in the mid-2000s, but has since taken on an identity of its own with the addition of thousands of self-published works that have been made available at no charge.

The browsing interface has a lot of room to improve, but it’s simple enough to use. Downloads are available in dozens of formats, including EPUB, MOBI, and PDF, and each story has a Flesch-Kincaid score to show how easy or difficult it is to read (perfect for improving your English


Perfect Your English Speaking Skills With These 5 Udemy Courses




Perfect Your English Speaking Skills With These 5 Udemy Courses

Learning English can be tricky. Grammar is one of the stumbling blocks. These five Udemy classes will help you speak and write English with better fluency.
Read More

).

free-ebooks-site-centsless

Unlike the other sites on this list, Centsless Books is a curator-aggregator of Kindle books available on Amazon. Its mission is to make it easy for you to stay on top of all the free ebooks available there.

Note that some of the “free” ebooks listed on Centsless Books are only free if you’re part of the Kindle Unlimited program, which may or may not be worth it for you


Kindle Unlimited — Is It Really Worth It?




Kindle Unlimited — Is It Really Worth It?

Amazon’s rumored "Netflix for books" service is finally here: Kindle Unlimited. In theory, it sounds fantastic. But is it all that it is hyped up to be?
Read More

.

Consider signing up to the free Centsless Books email newsletter to receive update notices for newly free ebooks and giveaways. The newsletter is only sent out on Mondays, Wednesdays, and Fridays, so it won’t spam you up too much.

Centsless Books also has a separate U.K. version of the site, which you may prefer if you’re from across the pond and tend to use Amazon UK instead.

free-ebooks-site-pdfbooksworld

Between the three major ebook formats — EPUB, MOBI, and PDF — it’s quite possible that you prefer the latter. You wouldn’t be the first, and you won’t be the last. PDFs have a lot going for them, including near universal support across platforms and several awesome PDF reader apps


The 6 Best PDF Readers For Windows




The 6 Best PDF Readers For Windows

Most people don’t stop to think about the PDF reader they install – they just install Adobe Reader. Adobe’s PDF Reader isn’t the only option, though – there are quite a few high-quality, free PDF…
Read More

.

If you want to stick to PDFs only, then you’ll want to check out PDFBooksWorld. It’s far from the largest ebook collection out there (a little over 1,000 titles at the time of writing) but they’re all free and all guaranteed to be PDF-optimized.

Note that you’ll need to create an account to use this site.

How Else Do You Get Free Ebooks?

In addition to the above, don’t forget about Amazon Prime! It now comes with something called Prime Reading


Amazon Adds 1,000 Free eBooks to Prime




Amazon Adds 1,000 Free eBooks to Prime

Prime Reading offers Amazon Prime subscribers unlimited access to more than 1,000 eBooks, magazines, short stories, comic books, and more. All for free.
Read More

, which grants access to thousands of contemporary ebooks in addition to all of the other benefits of Prime


6 Amazon Prime Benefits You Might Be Ignoring Right Now




6 Amazon Prime Benefits You Might Be Ignoring Right Now

Scratch the surface. Amazon Prime has so many more benefits that people have forgotten about or simply don’t realize exist.
Read More

.

If you’re already paying for a Prime membership, then these ebooks are essentially free. But if you don’t have Prime and don’t care about the other benefits, it may be hard to justify.

One last note: now that you have a bunch of ebooks waiting to be read, you’ll want to make sure you use a solid ebook reader whether you intend to read on a computer


5 Best PDF & Ebook Readers for Windows




5 Best PDF & Ebook Readers for Windows

Windows is establishing itself as a cross-platform operating system. It’s already running on tablets and 2-in-1 devices, making eBook reader applications for the desktop more relevant than ever.
Read More

or read on a mobile device


Don’t Like Amazon? Alternatives To The Kindle eBook Reader App For Android




Don’t Like Amazon? Alternatives To The Kindle eBook Reader App For Android

Amazon has its own set of flaws that send readers looking for an alternative that’s just as good. Looking to get away from Amazon, the Kindle, and DRM? Here are some of the best ebook…
Read More

.

Which sites do you find the most useful? Are there any other ways to get free ebooks that we overlooked? Share your thoughts with us down in the comments!

Image Credit: Tim RT via Flickr

Originally written by Aibek Esengulov on October 5th, 2008

via MakeUseOf.com
The Best 6 Sites to Get Free Ebooks

Citizen Persistence after NICS Gun Purchase Block Results in Overturn of Denial

By David Codrea

screenhunter_07-jan-05-19-01
Our bad — but your problem.

USA – -(Ammoland.com)- Lessons learned from one man’s struggle to challenge a gun purchase denial from the National Instant Check System give insights into how difficult it can be for a citizen to clear his name once the government has decided he’s a “prohibited person.” Fortunately, an Anchorage medical professional and “avid gun collector” [name withheld at his request] had the savvy, the wherewithal and the persistence to successfully fight a bureaucratic denial of his right to arms.

A former U.S. Army officer with a clean record that includes not so much as a speeding ticket in the past 10 years, albeit with one inadvertent self-reported fish and game violation in 2004, the doctor attempted to purchase a rifle at Cabela’s in Anchorage Alaska in early November. His first background check was delayed and then it was denied a few days later.

As an aside, the doctor says he has purchased many firearms over the last decade with no trouble. He immediately filed an appeal letter online and after multiple tries at trying to reach a live human, got a recording saying FBI was currently evaluating appeals from August 2015, putting them one year and three months behind even looking at his appeal.

“This was unreasonable,” he noted with extreme understatement, “so I created a plan to expedite my appeal. I immediately filled out my appeal online when I received the denial.

10929148_10153627186469852_7803755139904591303_n
Rep. Don Young sent inquiry to FBI.

“I contacted my congressman, Don Young, and his office sent a congressional inquiry to the FBI NICS,” the doctor continued. “And I completed my concealed carry course and turned in all the needed information to the background evaluation officer at the Alaska State Troopers. This agent evaluates your finger prints and other data to determine if you are eligible for your CCW permit. This agent also communicates with the FBI NICS.

“I sent another copy of my finger prints to NICS for evaluation,” he concluded. The end result was that the denial was overturned. The process took about four weeks vs. a year-and-a-half, but it required significant effort on my part.”

And the reason for the initial denial, for withholding a fundamental right for an undetermined period and without due process, and for making a citizen go through extraordinary measures, including recruiting the assistance of a United States Congressman in order to not get hung out to dry by a bureaucratic snafu?

“The fingerprints you submitted are not identical with those in a record used in the evaluation of your attempt to possess or receive a firearm,” a weasel-worded Department of Justice attempt at excuse-making without admitting fault (or heaven forbid apologizing for rejecting the wrong guy) offered as justification. “Based on further review and investigation, we have been able to determine you are eligible to possess or receive a firearm. The FBI Criminal Justice Information Services (CJIS) Division’s NICS Section Firearm Appeal Certificate is enclosed.

“If more than 30 days have elapsed since the initial background check, the FBI must recheck the NICS before allowing the firearm transfer,” the letter warned.

They had.

Reading about how bureaucratically rigid and wrong the government can be may make for forehead-slapping and head-shaking, but to a person trapped in their errors, it’s no laughing matter.  As Martin Luther King Jr. observed, “A right delayed is a right denied,” and that’s not supposed to happen under our Constitution without due process.

Researcher John Lott has documented the preponderance of “false positives” in his warnings against Brady background checks. That’s also a real danger in the latest bit of “bipartisan” rights denial being pushed under the “No Fly/No Buy” slogan. And it shows yet another downside to the Bloomberg “background check” mandates designed to end all private sales plus establish identifying data needed for a registration system (“Effectiveness depends on the ability to reduce straw purchasing, requiring gun registration…” — National Institute of Justice).

As noted, had this doctor been a person of lesser drive, someone who did not know how to go about righting a wrong and staying with it to completion, he’d still be in limbo. And there’s no guarantee the bureaucrats would make things right when they finally got around to trying to undo the sloppy work that led to the denial in the first place.

screenhunter_03-jan-07-09-59
A “happy ending” — that should have never had a beginning.
David Codrea in his natural habitat.

About David Codrea:

David Codrea is the winner of multiple journalist awards for investigating / defending the RKBA and a long-time gun rights advocate who defiantly challenges the folly of citizen disarmament.

In addition to being a field editor/columnist at GUNS Magazine and associate editor for Oath Keepers, he blogs at “The War on Guns: Notes from the Resistance,” and posts on Twitter: @dcodrea and Facebook.

This post Citizen Persistence after NICS Gun Purchase Block Results in Overturn of Denial appeared first on AmmoLand.com Shooting Sports News .

via AmmoLand.com Shooting Sports News
Citizen Persistence after NICS Gun Purchase Block Results in Overturn of Denial

Siren Care weaves electronics into fabric to keep diabetic patients healthy

Instead of tracking your health with a little band that’s on your wrist, Ran Ma thinks that the future is keeping track of your health — or at least parts of it — with technology that’s woven into the fabric of your clothes.

That’s the target of Siren Care, a wearable company that looks to weave electronic sensors into its clothing in order to track changes in a person’s health. The company is working on a sock that can track temperature changes in feet for diabetics, which can help figure out when things are starting to go wrong and the person needs to go to the doctor. Ma, who had previously studied wound care as part of her masters, thought this was the best place to start. Siren Care showed off the socks at a presentation at TechCrunch’s Hardware Battlefield at CES this year.

The sock is, well, a sock. It has a small device that protrudes from it that transmits information to the Siren Care app, which helps diabetic patients keep a close eye on what’s going on with the temperature changes in their feet. If there are any anomalies, they can take a look at what’s going on and figure out whether or not they need to go see a doctor before things get bad as a result of an injury that they weren’t keeping close tabs on.

Those injuries can be a result of something as simple as leaving a sock in a shoe, but the patient won’t be aware of what’s going on, Ma said. As a result, the problem can quickly spiral out of control and lead to a trip to the doctor or even worse. The goal is to ensure that, early on, that simply doesn’t happen and diabetic patients are able to have an extra tool to help manage it.

Throughout the launch and development, Siren Care will be working to gauge the overall change in a person’s health through what’s going on with their feet. That means that, instead of simply looking for a snapshot — like a spike in temperature or seeing an injury — it’ll be looking at trends and trying to get ahead of potential injuries, Ma said.

“Right now based on research there is an exact number that dictates when you have damage,” Ma said. “We think you can personalize that. Previous devices are a one-off measurement — how do you know what happened before or after? How do you know that wasn’t noise? We think we can do better because we’re taking continuous measurements throughout the day. Maybe your foot, one is always warmer than the other. We can account for that. Injury is not a spike in temperature, it’s a sustained average difference.”

siren care socks

To be sure, there’s a ton of interest in “smart” clothing that has electronics embedded in them. We’ve seen Kickstarter projects pop up like Enflux, which focuses on workouts, as well as other “connected” clothing like a jacket that’s built by Google and Levi’s. The technology is basically advancing to the point that the manufacturing process is getting easier to weave these kinds of electronics into fabrics in order to detect various changes around a person’s body.

The company went through 500 Startups and presented in October last year, and was definitely one of the standouts in the crowd. Siren Care for now works as a subscription model. The socks are machine washable, Ma said, and every six months Siren Care replaces the socks. That’s about average for other diabetic socks used to help spot injuries, though they can end up showing up later and it may be very far along and should have been treated earlier.

In the end, the company doesn’t plan at stopping at a sock for diabetics. The company is hoping to apply the technology — and the data it acquires through it — to build other kinds of smart clothing that is able to use the same processes of embedding sensors into fabrics. The applications of that are naturally pretty wide, so Siren Care is better off starting off with something they know they can tackle first, Ma said.

“I don’t see ourselves as a diabetic foot company. I think we’re a data company and next-generation wearables,” Ma said. “The next generation will be targeted toward chronic disease, aging, health management — and also in a way that’s designed to fit into your lives. Instead of having bands, it should be the clothes you wear every day.”

via TechCrunch
Siren Care weaves electronics into fabric to keep diabetic patients healthy