Ways to Fetch MySQL Query Result with PHP

Note: This post only covers mysql_fetch functions and not PDO codes which are more updated.

Hi guys, today we're gonna take a look at the ways to fetch MySQL query results with PHP. I found 6 ways of doing it. I'm going to enumerate each one with its corresponding name, description, sample code, and output.

I also provided the links to php.net if you want to learn more about these functions. You can also use this sample table and data if you want.

Ways to Fetch MySQL Query Result with PHP
PHP/MySQL: Ways to Fetch MySQL Query Result

We'll use the following example SQL query statement:

$sql="select id, firstname, lastname, username from users where id=28";

1. mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both. It returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row=mysql_fetch_array($rs);
echo "<pre>";
    print_r($row);
echo "</pre>";

Output:

Array
(
    [0] => 28
    [id] => 28
    [1] => John Michael
    [firstname] => John Michael
    [2] => Dalisay
    [lastname] => Dalisay
    [3] => john
    [username] => john
)

Use:

$id=$row['id'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
$username=$row['username'];

2. mysql_fetch_assoc() - Fetch a result row as an associative array

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row=mysql_fetch_assoc($rs);
echo "<pre>";
    print_r($row);
echo "</pre>";

Output:

Array
(
    [id] => 28
    [firstname] => John Michael
    [lastname] => Dalisay
    [username] => john
)

3. mysql_fetch_field() - Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row=mysql_fetch_field($rs);
echo "<pre>";
    print_r($row);
echo "</pre>";

Output:

stdClass Object
(
    [name] => id
    [table] => users
    [def] =>
    [max_length] => 2
    [not_null] => 1
    [primary_key] => 1
    [multiple_key] => 0
    [unique_key] => 0
    [numeric] => 1
    [blob] => 0
    [type] => int
    [unsigned] => 0
    [zerofill] => 0
)

4. mysql_fetch_lenghts() - Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row = mysql_fetch_assoc($rs);
$lenghts=mysql_fetch_lengths($rs);
echo "<pre>";
    print_r($lenghts);
echo "</pre>";

Output:

Array
(
    [0] => 2
    [1] => 12
    [2] => 7
    [3] => 4
)

5. mysql_fetch_object() - Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row=mysql_fetch_object($rs);
echo "<pre>";
    print_r($row);
echo "</pre>";

Output:

stdClass Object
(
    [id] => 28
    [firstname] => John Michael
    [lastname] => Dalisay
    [username] => john
)

6. mysql_fetch_row() - Get a result row as an enumerated array

Code:

$rs=mysql_query($sql) or die($sql.">>".mysql_error());
$row=mysql_fetch_row($rs);
echo "<pre>";
    print_r($row);
echo "</pre>";

Output:

Array
(
    [0] => 28
    [1] => John Michael
    [2] => Dalisay
    [3] => john
)

I usually use mysql_fetch_row and mysql_fetch_object. :)

How To Get A Job In Tech

How To Get A Job In Tech? Well, I currently have a job in the IT industry but not in these big and amazing  companies such as Google, Apple and Facebook. Honestly, I've been dreaming of getting a job at Google. Haha! I choose Google because I love their products such as GMail, Google Docs, Android, Search Engine and many others even though there are some ads, for me it's just fine and natural. It enable me to enjoy great technologies free. :)

But anyway, I'm happy with my current job, developing Google Android applications and utilizing lots of their web development tools such as of Google Code, Analytics, and Webmaster tools.

I wondered how to get at job in these awesome companies. So I thank this info-graphic for giving me some idea. Haha! Let's see:

 

Select All Records With Duplicates

I wanted to select all records with duplicate session numbers (session_number) from my forms table so I'll know if there are error of duplicate entries. I'm using MySQL Database.

Select All Records With Duplicates
Select All Records With Duplicates

Here's a solution I found:

SELECT session_number
FROM forms
GROUP BY session_number
HAVING COUNT( session_number) > 1

Explanation:

SELECT session_number
-I'm just selecting session_number

FROM forms
-I'm selecting records from forms table.

GROUP BY session_number
-This will group all the session_number.

HAVING COUNT(session_number) > 1
-After grouping the session numbers, we will count records with that group's session number. If it is greater than 1, it means it has duplicates, so it will be selected.

That's it! :)

Notepad++ Project Manager Plugin

Hi guys! just another quick and simple post. I found this one very useful when I’m developing a website or web app in my localhost – Adding a project explorer/manager to my favorite editor Notepad++. I really love Notepad++

Notepad++ Project Manager Plugin

To achieve it:

  1. Go to Plugins
  2. Plugin Manager
  3. Show Plugin Manager
  4. Plugin Manager Will Load Available Plugins
  5. Click on an item
  6. Press 'E'
  7. You’ll find ‘Explorer’
  8. Tick the checkbox
  9. Click install button!

To activate, go to Plugins > Explorer > Explorer, or just do Ctrl+Alt+Shift+E

That’s it!

When Apple Called Google, an Icon Ambulance

I thought Google and Apple are in conflict all of the time. I thought they hate each other so much because of Google Android and Apple iOS competition. But I was wrong. It is amazing for me to see that they treat each other as a friend. Vic Gundotra, the man behind Google Plus and also a Google Android Evangelist and Steve Jobs, the former Apple CEO and now its Chairman, seemed close to each other.

I think this is the real logo. :))

Here's the actual story, When Apple Called Google:

Icon Ambulance

One Sunday morning, January 6th, 2008 I was attending religious services when my cell phone vibrated. As discreetly as possible, I checked the phone and noticed that my phone said "Caller ID unknown". I choose to ignore.

After services, as I was walking to my car with my family, I checked my cell phone messages. The message left was from Steve Jobs. "Vic, can you call me at home? I have something urgent to discuss" it said.

Before I even reached my car, I called Steve Jobs back. I was responsible for all mobile applications at Google, and in that role, had regular dealings with Steve. It was one of the perks of the job.

"Hey Steve - this is Vic", I said. "I'm sorry I didn't answer your call earlier. I was in religious services, and the caller ID said unknown, so I didn't pick up".

Steve laughed. He said, "Vic, unless the Caller ID said 'GOD', you should never pick up during services".

I laughed nervously. After all, while it was customary for Steve to call during the week upset about something, it was unusual for him to call me on Sunday and ask me to call his home. I wondered what was so important?

"So Vic, we have an urgent issue, one that I need addressed right away. I've already assigned someone from my team to help you, and I hope you can fix this tomorrow" said Steve.

"I've been looking at the Google logo on the iPhone and I'm not happy with the icon. The second O in Google doesn't have the right yellow gradient. It's just wrong and I'm going to have Greg fix it tomorrow. Is that okay with you?"

Of course this was okay with me. A few minutes later on that Sunday I received an email from Steve with the subject "Icon Ambulance". The email directed me to work with Greg Christie to fix the icon.

Since I was 11 years old and fell in love with an Apple II, I have dozens of stories to tell about Apple products. They have been a part of my life for decades. Even when I worked for 15 years for Bill Gates at Microsoft, I had a huge admiration for Steve and what Apple had produced.

But in the end, when I think about leadership, passion and attention to detail, I think back to the call I received from Steve Jobs on a Sunday morning in January. It was a lesson I'll never forget. CEOs should care about details. Even shades of yellow. On a Sunday.

To one of the greatest leaders I've ever met, my prayers and hopes are with you Steve.

-Vic

Vic Gundotra posted this story on his G+ profile.

What I'm thinking now is this: Now that Google Android is getting the 50% of Smartphones Market Share, are they still friends just like on 6th of January, 2008? I think its a YES. Vic posted about this today, not a long time ago.

:)

Great Way to Upload, Resize and Crop an Image with PHP

Hi guys! Today I want to share with you a great way (well, at least for me) to upload, resize and crop an Image with PHP. We’re gonna use a class here. I found this class really amazing and works well. This class is really easy and simple to implement.

Great Way to Upload, Resize and Crop an Image with PHP
Great Way to Upload, Resize and Crop an Image with PHP
DOWNLOAD SOURCE CODE

This is how I used it:

<html>
    <head>
        <title>Upload, Resize and Crop an Image with PHP - https://www.codeofaninja.com/</title>
     
    </head>
<body>
<?php
if( isset($_FILES['image'] ) ) { //if the image was uploaded
    //include our class
    include 'libs/img_upload_resize_crop.php';
     
    //instantiate our class
    $your_image = new _image;
     
    //To Upload
    //set the location
    $your_image->uploadTo = 'uploads/';
    $upload = $your_image->upload($_FILES['image']);
    echo "<div>" . $upload . "</div>";
     
    //To Resize
    $your_image->newPath = 'thumbs/';
    //set new image dimensions
    $your_image->newWidth = 400;
    $your_image->newHeight = 300;
    $resized = $your_image->resize();
    echo "<div>" . $resized . "</div>";
     
    //To Crop
    //dimensions of cropped image
    $width = "150"; 
    $height = "100";
    //we will supply coordinates so that the class would
    //know what part of the image we want to start cropping
    $fromX = "0"; //x coordinate
    $fromY = "0"; //y coordinate
    $your_image->newPath = 'cropped/';
    $cropped = $your_image->crop($width,$height,$fromX,$fromY);
    echo "<div>" . $cropped . "</div>";
     
    echo "Image was successfully uploaded.";
}
?>
<!-- Create your form -->
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <div><input type="file" name="image" id="image" /></div>
    <div><input type="submit" name="button" id="button" value="Submit" /></div>
</form>
</body>
</html>

If you want more configuration of this class for example you want to decrease the image quality, etc., you can check the class’ code which is found in libs/img_upload_resize_crop.php and set your values there.

I run the script and after browsing the image and hitting the submit button, it look like this:

after-submit

So I got what I want to do with my image after uploading it. Easy and simple right? Thanks to MJDigital.

Computers – A Chronological Timeline

In this post, we'll take a look at the chronological timeline of computers. I like the infographic below so I thought it will be great to share it with you. I also suggest you visit the Computer History Museum.

I love computers. This is where I do most of my stuff. I do Web and Android programming. I made my dream of being a writer come true by blogging, connecting with friends via social networking sites such as Facebook and Twitter.

I was able to do research, have a conversation with other Software Developers around the world via StackOverflow and other Q&A or forum sites, help and inspire others, play games such as Angry Birds and Red Alert, etc. 

My career wouldn't exist without it. Computers changed the world - how we work, think, and live. Most businesses in the world won't run without computer systems, and they won't get promoted without a website.

So, it is such a joy to see some of its histories, how it evolved from generation to generation.

It was so nice that I came across this infographic here. :)

Transfer WordPress Site From Local Computer to Server Without Reinstalling

Recently, I had to develop a website with a famous CMS - WordPress. I have version 3.2.1. I'm so happy with it, the last time I worked with WordPress was about 3 years ago, and I didn't appreciate it the way I appreciate it today.

Transfer WordPress Site From Local Computer to Server Without Reinstalling
From your computer to your server.

So here's what I went through, I have WAMP on my computer and so I downloaded WordPress, installed it locally and tried to play around with it. I downloaded free WordPress themes, modified them, saved articles, etc. So now, I thought that the WordPress site I worked on my computer is good enough to be online. I never thought setting up a website with WordPress is this easy.

So I uploaded my files to the server and exported the SQL database. I tried to browse the site and guess what, tons of errors were shown. I didn't want to do a new WordPress installation on my server. So I had to hack some WordPress settings. Here's what I did:

1. Export SQL from local PhpMyAdmin to online PhpMyAdmin (If you're using PhpMyAdmin)

2. Copy WordPress files from localhost to server using Filezilla (or any FTP software)

3. Login and then create your online database with the same database name you have locally

4. Browse wp_options table

5. The first row (siteurl) contains your local url, probably http://localhost/YouSiteName, you have to change that to your online domain such as http://YourSiteName.com/

6. So now you can login to your online admin panel http://YourSiteName.com/wp-admin/

7. After logging in, Go to Settings > General

8. Change the site address (URL) to http://YourSiteName.com/, then hit save button

9. Again, Go to Settings > Permalinks

10. At the bottom part of it, you will see the correct .htaccess code.

Transfer WordPress Site From Local Computer to Server Without Reinstalling
Click to enlarge.

11. Copy it and access your current online .htaccess file and then paste the new .htaccess code, save and re-upload

That's it! Now you have successfully transferred a WordPress site from your computer to Online server without reinstalling!