Php / Html - database disconnect - php

I have a working php code which simply connects database lists the data and closes it.
I embedded this working php code into my html but it does not parse the rest of the html. It is simple blank after listing data from database and php close tag " ?> ". I tried to get rid of " $db->disconnect(); " in php and now it works.
Do you have any idea why?
Do i really need to use $db->disconnect(); every time?
Thanks
beginning of the html code
<ul>
<?php
$db = new mysqli('localhost', 'root', 'root', 'troy');
if (mysqli_connect_errno()) {
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
$query = "SELECT * FROM platters";
$result = $db->query($query);
while($row = mysqli_fetch_array($result)) {
echo "<li>" . $row['name'] . "</li>";
}
$db->disconnect();
?>
</ul>
rest of the html code

$db->disconnect(); is not listed under the documentation, is this a custom function that you have created?
Instead of disconnecting the entire database connection, you should just perform:
$result->close();
this will free up the current query, and enable you to perform further connections throughout that PHP Script.
Only close the connection to the database entirely if you are done with your SQL Connection for that script
Edit
After re-reading your question, $db->disconnect(); is not a function for MySQli. See the entire documentation here:
http://php.net/manual/en/book.mysqli.php
You should use:
$db->close(); which closes the current connection to the database (if used on your database variable)
http://www.php.net/manual/en/mysqli.close.php

Run it on the command line
php test.php
and see the error message
PHP Fatal error: Call to undefined method mysqli::disconnect() in test.php on line 28
This is the reason, why it outputs everything from the database, but omits everything after that line.
When you remove the $db->disconnect(); statement, the error is gone and the PHP script can work it's way until the end.

Related

Why is my PHP short-code printing text instead of performing function when trying to connect to MYSQL database on Wordpress?

I'm trying to display a table from my MYSQL database on a website I'm creating on Wordpress. I'm using the code shown in the code block. This code is within a PHP short-code snippet and added to a Wordpress widget. Once I get past the ">" of <your-MySQL-database-password>, the short-code seems to screw up, and starts to print the text of the code as opposed to actually making the connection. The text that prints is:
, ,'', 'Connect'); if (!$conn){ echo 'Connection error:
mysqli_connect_error(;}?>
When I delete the ">" at the end of <your-MySQL-database-password> all of the printed text disappears except for the `, , at the very beginning.
<?php
$conn = mysqli_connect(
<location-of-your-database>,
<your-MySQL-database-username>,
'<your-MySQL-database-password>',
'Connect');
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
?>
I suspect if I had a better fundamental knowledge of PHP I could figure this one out pretty easily.
Writing the text into the short-code and skipping the snippet
Creating the snippet and entering the snippet identifier into the short-code block (same result as 1.)
Deleting characters to see what's effecting the rest of the code.
Looked up to see what issues people have with snippets/shortcode on Wordpress
This might helps
<?php
$con = mysqli_connect("localhost","your-db_username","your-db_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>

PHP - Error handling while querying mysql

I am new to web development, so probably there is something I am doing it wrong.
I am using webmatrix for development and playing around with StarterSite sample that webmatrix provides.
In one of the php file (header.php) there is a query to mysql using mysqli extension. I have changed the tablename to some non existent table to simulate error condition. The problem is, after below statement -
$statement->execute();
the script stops.
I inserted a echo statement after execute and that echo string is not displaying on webpage. However when I correct the table name, the echo string after execute is displayed on webpage. So I think the script stops executing after execute when the table name is wrong. I have two questions. How do I stop script from stop executing like this? Secondly How to know for sure that script has stopped executing at some particular statement?
For second part of question, I checked the log file and tracelog file in IISExpress folder. There is no mention of any error, probably because error happened in MYSQL. However, in my MYSQL folder there is no log file, so not sure how to check mysql log.
If I have missed anything, please let me know.
Regards,
Tushar
You should read about mysqli error handling.
Basic error handling example OOP:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Procedural:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
It depends on what you're logging. In the error log you can define what's being logged. I think you can control the strict mode of the error in the php.ini which will automatically throw error into the access_log or error_log or apache log file.
The trick is to use $mysqli->error in every step of the mysqli querying and db connects to ensure you're getting proper error messages in detail whether to debug, improve the code or to do it correctly.
Here is an example of using $mysqli->error in querying the database.
$result = $mysqli->query($query);
if (!$result and $mysqliDebug) {
// the query failed and debugging is enabled
echo "<p>There was an error in query: $query</p>";
echo $mysqli->error; //additional error
}
You can also use a method where you define mysql error to be true in db conn
// define a variable to switch on/off error messages
$mysqliDebug = true;
// connect to your database
// if you use a single database, passing it will simplify your queries
$mysqli = #new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
// mysqli->connect_errno will return zero if successful
if ($mysqli->connect_errno) {
echo '<p>There was an error connecting to the database!</p>';
if ($mysqliDebug) {
// mysqli->connect_error returns the latest error message,
// hopefully clarifying the problem
// NOTE: supported as of PHP 5.2.9
echo $mysqli->connect_error;
}
// since there is no database connection your queries will fail,
// quit processing
die();
}
#ref: https://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking

How to connect to remote database on Wordpress

Probably been covered but I keep getting "connecting to the Wordpress database" which isn't what I'm after. In a nutshell I have a perfectly fine Wordpress site, I also have a MySQL database on another server which has some data I'm after. The code works fine on phpfiddle (is this the standard?) but whenever I try to use it on the Wordpress site, either with shortcodes or in the header.php it keeps hanging, throwing errors and won't connect to the DB, any ideas why?
Edit: To make things clearer, it's a meteorological database I want to connect to in order to pull things like Temperature from. Nothing native or related to Wordpress.
<?php
// Create connection
$con=mysqli_connect("ip","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
Gives me this
Warning: mysqli_connect(): (HY000/2003): Can't connect to MySQL server on...
You should probably be looking at the WordPress WPDB class - https://codex.wordpress.org/Class_Reference/wpdb
For example:
<?php
$wpdb_dbconnect = new wpdb(user, pass, db_name, localhost);
$wpdb_dbconnect->show_errors();
$object = $wpdb_dbconnect->get_results("SELECT * FROM table_name");
foreach ($object as $person) {
echo $person->name . ', ';
}
?>
To connect to a second (and third, and forth...) database, I recommend HyperDB plugin.

SQL query err_empty_response

I have a problem when executing a simple piece of code:
$con=mysqli_connect($host,$user,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM exercises");
if (mysql_num_rows($result) > 0) {
}
The variables on the first line are imported from another file. Everything works until I try to do anything with the $result variable. I can get the result from the database without an error, but as soon as I start doing something with it in an if statement or a loop (to fetch the results), my page will simply not load, and I get an err_empty_response. I tested it in multiple browsers. Also, some other of these issues on stackoverflow did not seem to have the soultion to the problem.
All help is appreciated.

Could anyone with MySQLi experience help me with this short SELECT code?

I have researched my question but there just isn't much help out there for MySQLI functions. I'm also new here so, please bear with me.
I have a test database named "website" and it contains a table called "users" which has data for all of the members of my website. In a separate file I have the php code that connects to my localhost and selects the database "website." I'm using the newest functions of MySQL so instead of the connection string containing mysql_connect it contains mysqli_connect. The registration process works great and I can find no error in any of the other code that uses the mysqli functions.
My include file (connect.php)
<?php
$link = mysqli_connect("localhost", "useracc", "useracc1", "website");
?>
I set up a test script for the login section.
<?php
include('connect.php');
$user = $_POST['user'];
$query = "SELECT birthday FROM users";
$result = mysqli_query($link, $query) or die ("RESULT ERROR");
echo "$user";
echo "$result";
?>
There is a password box on the previous page but for the test script I left that out and so far, only the $user is shown on the page. I get no error even when I replace "RESULT ERROR" with mysqli_error($link). I've tried interchanging ' for " in every part of the code that uses quotes but that didn't work. I've tried rewording the $query line but that also had no effect. I'm really new to MySQL and php so if you guys could tell me where I'm going wrong I'd really appreciate it.
Thanks for reading my question. Have a great day.
Add the following lines to the connect.php after you connect line
if (mysqli_connect_errno()) {
printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
exit;
}
this will ensure the connection is made without any errors and return them if there are ...

Categories