Solved

Tweaked MySql Connection - Now Select Query's Fail

Posted on 2016-07-30
13
55 Views
Last Modified: 2016-08-01
Hi Guys'

Yes it me again ...

I've updated some of php pages to include an access control function which works great - super pleased about that! However, the code I've used seems to conflict with select queries I've previously written.

Can you tell me what causes the problem please if I post some examples below?

Previously my config.php file looked like this: -

<?php


	/* Access to the databse via link commands requires the $link statement
	in order for them to be successful, also the term "localhost" stops the $link
	failing in the event of a change in your IP Address.*/
	
	$link = mysqli_connect("localhost" , "user", "password", "DbName");


?>

Open in new window


Now it includes some access control functions and the config file looks like this:

// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost";
$db_name = "DbName";
$db_user = "user";
$db_word = "password";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

Open in new window


The first config allowed the following select queries to run: -

<?php
	
	$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`,	`sales14D`, `supplierCompany`, `itemCost` FROM inventory";
	
	if ($result=mysqli_query($link, $query)) {
	
		while ($row = mysqli_fetch_array($result)) {
		
	?>
			<tr>
			<td><?php echo $row['partID'];?></td>
			<td><?php echo $row['partDescription'];?></td>
			<td><?php echo $row['qtyInStock'];?></td>
			<td><?php echo $row['sales42D'];?></td>
			<td><?php echo $row['sales14D'];?></td>
			<td><?php echo $row['supplierCompany'];?></td>
			<td><?php echo $row['itemCost'];?></td>
			</tr>
						
<?php
		}
	
	} else {
	
		echo "It failed!";
	
	}
?>

Open in new window


The 2nd config files causes the connection to fail ... what am I doing wrong?

Thanks J
0
Comment
Question by:Ridgejp
  • 7
  • 6
13 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Without a test case, we have to guess a little bit, but I think this is an educated guess.  

PHP has two ways of using the MySQLi extension.  One is procedural and one is object-oriented.  Details in the man pages here (for the connect() or __construct() functions):
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.construct.php

As written, the functions return different variables.  
$link = mysqli_connect("localhost" , "user", "password", "DbName");
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

Since $link is not the same as $mysqli, the rest of the code cannot use $link or $mysqli interchangeably.  My recommendation is to use the object-oriented notation with $mysqli, and dispense with the procedural notation entirely.  The primary reason for this recommendation is that object-oriented programming is more susceptible to automated testing, and is more in line with modern design patterns.  Procedural programming kind of went into the rubbish bin at the end of the 20th century.  It's also easier to swap out the old, obsolete mysql statements for the object-oriented mysqli statements.

Details are available in this article, including tested-and-working examples.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

It's also syntactically easier to use the object-oriented fetch method.  No need to flop back and forth between PHP and HTML.  Fewer fiddly punctuation marks means fewer parse errors, too.  Greater programmatic flexibility since the rows are returned in the form of objects instead of arrays.  Here's an easier and more efficient way to write the code (untested but probably correct in principle):
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    trigger_error( /* FAILURE DIAGNOSTICS */, E_USER_ERROR);
}
while ($row = mysqli_fetch_object($result)) {
    $row = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $row;
}

Open in new window

0
 

Author Comment

by:Ridgejp
Comment Utility
Hi Ray,

My query looks like this now, however, the pages fails to load at all ... did I do something wrong? Thanks for the links too more bedtime reading ... your section on access_control() was great!

</div>
		
		<table id="table" class="table table-striped">	
			<thead>
			<tr>
				
			
			<th class="success">partID</th>
			<th class="success">Description</th>
			<th class="success">stockQty</th>
			<th class="success">sales42D</th>
			<th class="success">sales14D</th>
			<th class="success">supplier</th>
			<th class="success">itemCost (£)</th>
			
			</tr>
			</thead>
			<tbody class="searchable">
			
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    trigger_error( /* FAILURE DIAGNOSTICS */, E_USER_ERROR);
}
while ($row = mysqli_fetch_object($result)) {
    $row = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $row;
}
		</table>
</div>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Sorry, my "cut and paste" mistake.  I never use the procedural code, and sometimes forget to ferret it out!  Try it like this (line 8, et seq):
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    trigger_error( /* FAILURE DIAGNOSTICS */, E_USER_ERROR);
}
while ($row = $result->fetch_object()) {
    $tr = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $tr;
}

Open in new window

Also, you might want to include some kind of "failure diagnostics" instead of the comment.  If the query ever fails, you'll want to be aware of the issue.
0
 

Author Comment

by:Ridgejp
Comment Utility
Still no joy sorry ... although I've noticed that the opening table statement is no longer linked color-wise to the closing table statement. I'm using brackets to code my php.

Screenshot and code attached ...

<table id="table" class="table table-striped">	
			<thead>
			<tr>
				
			
			<th class="success">partID</th>
			<th class="success">Description</th>
			<th class="success">stockQty</th>
			<th class="success">sales42D</th>
			<th class="success">sales14D</th>
			<th class="success">supplier</th>
			<th class="success">itemCost (£)</th>
			
			</tr>
			</thead>
			<tbody class="searchable">
			
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    trigger_error( /* FAILURE DIAGNOSTICS */, E_USER_ERROR);
}
while ($row = $result->fetch_object()) {
    $tr = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $tr;
}
		</table>

Open in new window

0
 

Author Comment

by:Ridgejp
Comment Utility
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Well, we are still looking at fragments, so we need to do some diagnostics.  After the connection, please add var_dump($mysqli).  Then add the diagnostics in place of the comment, /* FAILURE DIAGNOSTICS */.  The general design for the diagnostics can be found in the article here:
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

In that article, look for the part about Create and Execute a SELECT Query.  You can copy the diagnostic code from the MySQLi example where it says "IF mysqli_query() RETURNS FALSE, LOG AND SHOW THE ERROR."  Hopefully, after we add the diagnostics to the script, we will get a signal of what went wrong and we can fix that.
1
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Ridgejp
Comment Utility
Is this correct now Ray - struggling a little with it?

</div>
		
		<table id="table" class="table table-striped">	
			<thead>
			<tr>
				
			
			<th class="success">partID</th>
			<th class="success">Description</th>
			<th class="success">stockQty</th>
			<th class="success">sales42D</th>
			<th class="success">sales14D</th>
			<th class="success">supplier</th>
			<th class="success">itemCost (£)</th>
			
			</tr>
			</thead>
			<tbody class="searchable">
			
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    ;
    trigger_error($err, E_USER_ERROR);
}

var_dump($mysqli); 
                
while ($row = $result->fetch_object()) {
    $tr = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $tr;
}
		</table>
</div>
       

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Maybe a bit more like this (variable names have to be used consistently).  How does it test out?
</div>
        
        <table id="table" class="table table-striped">  
            <thead>
            <tr>
                
            
            <th class="success">partID</th>
            <th class="success">Description</th>
            <th class="success">stockQty</th>
            <th class="success">sales42D</th>
            <th class="success">sales14D</th>
            <th class="success">supplier</th>
            <th class="success">itemCost (£)</th>
            
            </tr>
            </thead>
            <tbody class="searchable">
            
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    $err
    = "QUERY FAIL: "
    . $query
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    ;
    trigger_error($err, E_USER_ERROR);
}
                
while ($row = $result->fetch_object()) {
    $tr = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $tr;
}
        </table>
</div>

Open in new window

0
 

Author Comment

by:Ridgejp
Comment Utility
All changed ... but still not loading page. J
</div>
        
        <table id="table" class="table table-striped">  
            <thead>
            <tr>
                
            
            <th class="success">partID</th>
            <th class="success">Description</th>
            <th class="success">stockQty</th>
            <th class="success">sales42D</th>
            <th class="success">sales14D</th>
            <th class="success">supplier</th>
            <th class="success">itemCost (£)</th>
            
            </tr>
            </thead>
            <tbody class="searchable">
            
<?php
    
$query = "select `partID`, `partDescription`, `qtyInStock`, `sales42D`, `sales14D`, `supplierCompany`, `itemCost` FROM inventory";
    
if (!$result = $mysqli->query($query)) {
    $err
    = "QUERY FAIL: "
    . $query
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    ;
    trigger_error($err, E_USER_ERROR);
}
                
while ($row = $result->fetch_object()) {
    $tr = <<<EOD
            <tr>
            <td> $row->partID </td>
            <td> $row->partDescription </td>
            <td> $row->qtyInStock </td>
            <td> $row->sales42D </td>
            <td> $row->sales14D </td>
            <td> $row->supplierCompany </td>
            <td> $row->itemCost </td>
            </tr>
EOD;
    echo $tr;
}
        </table>
</div>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Parse error on line 50, maybe?  It looks like you might need to close out PHP and go back to straight HTML there.

Are you using a framework or CMS in this application?
0
 

Author Comment

by:Ridgejp
Comment Utility
Can't believe I missed that ... pop that in now and see what happens. I'm building each page from scratch piece by piece to replicate what my MS_Access Db achieves for my business so pushing myself a little so I guess that means I'm using framework as I'm not writing it within a Content Management System if that's what you mean?

Report back shortly ... thanks for sticking with me on this one.
J
0
 

Author Comment

by:Ridgejp
Comment Utility
Bingo! Query loads successfully thanks for all your help - I just need to research what everything you included means so that I can better understand how to mod the other queries.

Thanks again ... J
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Glad to help, and best of luck with it! ~Ray
0

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now