I'm trying to insert some data into a DB on my local machine.
I've opened up the connection, and performed the INSERT INTO for the fields I require. Nothing is showing up in the database but I'm really lost as I'm not getting any errors either, so no guidance as to where it is failing. I have tried scaling it back and adding in echo variables to check how far the script is running but it runs all the way to the end.
To start I set the password and username which is just my local stuff:
// configuration
$dbuser = "root";
$dbpass = "";
Then I create the connection
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"survey");
Because I was struggling to find out where it was falling over, I have included an error statement. At present it outputs 'successfully connected' so it's not failing to connect...
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo 'successfully connected';
}
And then I'm preparing the SQL INSERT INTO
// the SQL insert
mysqli_query($con,"INSERT INTO mytablename (MostImportantFeatures,ImportanceOfFreeDelivery)
VALUES ($features,$importance_free_delivery)");
mysqli_close($con);
And I am getting nothing back. No errors, but no submission to the database. I cannot work out where I've gone wrong or how I can debug this as the script runs through. I can log into the database (using Sequel Pro) with the details above just fine.
How would you start to debug this?
To start debugging you probably want to check if you get TRUE or FALSE back from mysqli_query, and check the last error on false.
if(!mysqli_query($con,"INSERT INTO mytablename (MostImportantFeatures,ImportanceOfFreeDelivery) VALUES ($features,$importance_free_delivery)")) {
echo mysqli_error($con);
}
mysqli_query docs - php.net
mysqli_query docs - php.net
Related
I have created some PHP code for my website to call a stored procedure in my database. This will get text from a table so that I can dynamically update the text on the web page without modifying it in code.
This part works very well so far. However, When I open the MySQL error log I see the following message printed:
Aborted connection 161 to db: 'dbname' user: 'username' host: 'localhost' (Got an error reading communication packets)
I have checked the firewall, which is inactive.
I have attempted using 127.0.0.1 instead of localhost in the PHP code.
I have cleared the results using "mysqli_free_result($result);", this did seem to remove one of the two errors I got per query.
I have checked the max allowed packet size, which is 16M.
I have un-commented the extension mysqli in the php.ini file.
PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "password ";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "Call StoredProcedure('primarykey',#OutValue);";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ColumnHeader"];
}
} else {
echo "0 results";
}
mysqli_free_result($result);
$t_id = mysqli_thread_id($conn);
mysqli_kill($conn,$t_id);
mysqli_close($conn);
?>
SQL:
CREATE DEFINER=`username`#`hostname` PROCEDURE `StoredProcedure`(IN PrimaryKey
VARCHAR(50), OUT Result VARCHAR(50))
BEGIN
start transaction;
select ColumnName
from dbname.tablename
where PrimaryKeyColumn = PrimaryKey;
commit;
END
As I mentioned, I am getting the expected result from my query and it is perfectly functional, so I am not sure what can be the cause.
The server is running MySQL version 5.7.27-0ubuntu0.18.04.1((ubuntu)). Any help with this would be greatly appreciated!
Update - 11/Sep/2019:
I have attempted to check how long the execution of the my PHP script takes. To do this I added the following code borrowed from this thread:
Tracking the script execution time in PHP.
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
However, the result was the following:
This process used 0 ms for its computations It spent 1 ms in system calls
Which should not cause any timeouts.
I also activated the general log file on the server and i did see that the it would track the query as follows:
Command Type, Detail
Connect, username#hostname on dbname using Socket
Query, Call StoredProcedure('PrimaryKey', #result)
I am curious about there being no log saying disconnect though I do not know if this is default behaviour from MySQL.
Another curious thing I discovered was that MySQL Workbench states my query time for the stored procedure is on average 7ms but all resources I could find states that PHP waits for the query to finish before continuing.
Query, Total Time, Max Time, Avg Time
CALL StoredProcedure ( username # hostname ) , 98.94, 66.26, 7.07
In short, I still have not found any solutions to the issue, but potentially some leads that could eventually lead to a resolution.
Update - 18/Sep/2019:
After more digging on the issue I've come across the following thread:
https://dba.stackexchange.com/questions/144773/mysql-aborted-connection-got-an-error-reading-communication-packets
It is suggesting that due to MySQL and PHP being installed on the same server, they are competing for RAM. Considering my server is running on a Raspberry Pi 3 model B, this seems like a plausible explanation for the issue I am facing.
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
First off, I'm a total noob in mysql(i) language and know a little more than the basics of PHP.
Note: I do not manage or own / have access to the server on which the webpage currently is hosted. I can however access the phpMyAdmin page.
That said, I've got a webpage on which I am trying out some stuff. Right now I'm trying to make a log-in page linked to a database.
Now, behold the code:
$mysql_host = "localhost";
$mysql_user = "my_user";
$mysql_database = "my_database";
$mysql_password = "my_password";
$table = "my_tablename";
// Create connection
$con=mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// sending query
$result = mysqli_query("SELECT * FROM my_tablename");
if (!$result) {
echo "Query to show fields from table failed! :-(";
}
Now, here comes the actual problem. As soon as I launch the page it will give me my "Query to show fields from table failed!" error message. But when I enter the same query on the phpMyAdmin 'SQL' tab, I get the wanted results. How come the webpage gives me an error, while the phpMyAdmin gives me the results, and, how do I solve it?
Use correct syntax:
$result = mysqli_query($con, "SELECT * FROM my_tablename");
You forgot to link current mysqli connection. First parameter is link - which mysqli connection you want to use (good for multiple conns) and then the second is your query.
I tried using this code to input data from a form into a database, but the code will not work and it keeps giving me access denied and error messages.I will submit my php code and a screen shot of the error messages in the hopes that you can find out why this dose not work.
Code & Screen Shot Below:
<?php
// Create connection
$con=mysqli_connect("<host>","<username>","<password>","<database>");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO usertb (username, password)
VALUES
('$_POST[username]','$_POST[password]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Access denied would point to a DB connection error. Without seeing the error message I would say its one of two possibilities, db user being denied a connection to the DB or the user not having enough rights on the DB to be able to make changes.
Confirm that you can log into the DB with the user information you have put in you code.
mysql -D 'db name' -u 'user' -p
If you can get in OK, see if your INSERT query works at the mysql command line. If it does then you know your user can enter data into that DB and you know your query is properly formed.
If the above works all OK, then you know there is something wrong with your PHP code.
Lastly I would put a positive response on your connect and query code.
$con=mysqli_connect("<host>","<username>","<password>","<database>");
// Check connection
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "Connected to DB successfully!<br>!";
}
Hopefully that gets you a little closer.
S
I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.