PHP mysqli statement execute() not working - php

I havn't found something equally on stackoverflow.com, so i post my question in the hope someone have an idea what's wrong with my code or something i'm using.
Before i begin: On my productive webspace the same code works, the problem is located at the xampp-installation for my local development-server... sigh
I have a little webapplication for my family and me to document the work at home (e.g. to empty the bin), so we can distribute money to our kids, depending on how much they done by themself (a little bonus to the pocket money they get without homework)
The code to insert a line into my db-table is:
function AddGarbEntry($DBConnection, $DBPrefix, $UserID, $GarbID)
{
$stmt = $DBConnection->prepare("INSERT INTO t_".$DBPrefix."_entries (idUsers,idGarbType) VALUES (?,?)");
$stmt->bind_param("ii", $UserID, $GarbID);
$stmt->execute();
$stmt->close();
}
The part of the script, where i call this function is:
$con = new mysqli($_SESSION["DBHost"], $_SESSION["DBUsername"], $_SESSION["DBPassword"], $_SESSION["Database"]);
AddGarbEntry($con, $DBPrefix, $_POST["user"], $_POST["garbagetype"]);
$con->close();
I've already checked the Session-Variables (They are all filled with the correct values), and the POST-Values (They are filled correct either).
In my MySQL-Log a can find the following lines:
170423 11:54:38 66 Connect rldmla_1#localhost as anonymous on rldmla_db1
66 Prepare INSERT INTO t_garb_entries (idUsers,idGarbType) VALUES (? , ?)
66 Close stmt
66 Quit
So, i can see, that the prepare is working, but there is no sign, that my testserver runs the execute()-Command. The error-logs of php, apache and mysql have no entry about that.
Curiously, if i'm using a specific function of my website to update already existing lines (also prepared-statement, but an update-statement), my insert code works properly for about two times, after that it stop working until i update my table again.
I've tried the actual version of xampp (7.1.x) and the older version (7.0.15), but the problem is the same. Xampp is running as x86-version on a x64-running Windows Server 2012-Machine. I've only installed the modules Apache, PHP and MySQL.
I don't have any clue, what i'm doing wrong. Any help is appreciated.
Greetings, Ronny

Urks.... Now I've got the clue:
I changed my Xampp-Installation to a linux based virtual machine, where i've installed Apache, PHP, MySQL and phpMyAdmin. After that the missing execute-line was in the MySql-Logfile.
So, nothing to do here anymore.
Thx #all for supporting me :)
Greetings, Ronny

Related

Why is the mysqli->$errno being set to 0 in the middle of the debugging?

Today I am faced with a bizarre situation. I have been searching for a definition but unfortunately, I couldn't find any.
In my PHP code, I am inserting a row into a database table. When I try to insert a duplicate primary key as part of debugging a recent issue, I can see the duplicate primary key exception in the mysqli object as expected.
However, mysqli->$errno, mysqli->$error, mysqli->error_list are immediately being reset to empty which I cannot comprehend why.
This is part of the code that I am experiencing the issue with.
$retry = 5;
do {
$mysqli_result = mysqli_query($conn, $sql);
if (mysqli_errno($conn) == 1213) { /** Here I can observe the expected errno, error, error_list **/
sleep(1); $retry--;
} else
$retry = 0;
} while ($retry);
/** Here - errno, error, error_list are reset to empty */
Update
I have also noticed that along with the change that I mentioned the mysqli->$stat is also changing. Or is it like when the stat is queried everything else is reset?
Some additional info
This is an old project made using PHP 5.6 [95% compatible with up to PHP 7.2]. So I am using 7.2 in my local environment. Don't advise me to upgrade the whole project please, I know its already dead. I am just maintaining the project
The variable $conn is global
I am using vscode and compatible Xdebug extension for watching the variables
I am observing this behaviour when there is a slight delay in stepping over the current statement.
I'm sorry to say this but it looks like the problem is that you are using an unsupported PHP version. The broken mysqli::$stat property was removed in PHP 7.4. The solution is to upgrade your PHP version.
When triggering any MySQLi function the error and error properties are reset. You have to check it immediately after calling each function.
For example:
$mysqli->stat();
if($mysqli->error) {
// ...
However, I would strongly recommend to forget about ever using error and errno properties. Just enable automatic MySQLi error reporting and stop checking for errors manually.
When using xDebug the properties will never be shown to you correctly due to this MySQLi bug.
I know you can't afford it now, but please always consider using PDO rather than MySQLi. PDO is much better and easier.

Codeigniter command line can't inset to database

I have this function on 'myproject/controllers/sample.php'
public function callTest()
{
$this->load->database();
$this->db->query("INSERT INTO table_name (client_id, subscription_id, platform, device) VALUES (1, 1, 1, 1)");
$this->load->view('sample');
}
Whenever I run it on the browser (localhost/index.php/sample/callTest), it successfully runs and inserts the data on the table, but when I use command line (php index.php sample callTest), the SQL won't run.
I removed the database part and it shows the code for the view, which I think is correct. But if I put a database logic to it, it won't run and the output is blank. No error logs also.
Am I doing something wrong? Am I missing an argument?
My codeigniter version is 2.2.6.
This is my reference https://www.codeigniter.com/userguide2/general/cli.html
Edited: Aril 17,2017
I just figured out that in some of environment, the command line above works. I suspect that the cause of this was me converting PHP 5.5 to 5.6 in Ubuntu 14, some of the dependencies might not be configured correctly.
You need to specify controller and function name as well,
Example
php index.php/sample/callTest
Also you need to set one config variable as below
$config['uri_protocol'] = 'AUTO'
Read the document answer is hidden there.
Now normally you would visit the your site using a URL similar to
this:
example.com/index.php/tools/message/to

PHP Fatal error: Call to a member function num_rows() on a non-object

I am working with MySQL in conjunction with ExpressionEngine 2.2.1. This version of ExpressionEngine automatically comes with a Query Module, which I am using to filter and display entry results from a module called Freeform. I am using Freeform version 3.1.1. All of these elements are working well together and displaying the desired results on my local setup. However when I push my code to production, I am receiving this error:
Fatal error: Call to a member function num_rows() on a non-object in /var/www/vhosts/xxxxxxxxx.com/systemxxx/expressionengine/modules/query/mod.query.php on line 183
Here is this section of the code beginning on line 183 of mod.query.php (I did not code this php, nor have I ever coded php, this was already included with the site that I am working on.):
183 if ($query->num_rows() == 0)
184 {
185 return $this->return_data = $this->EE->TMPL->no_results();
186 }
Here is how I am using the Query Module in my HTML Template:
{exp:query sql="SELECT first_name, last_name, email, city FROM exp_freeform_entries WHERE city = 'New York'"}
<tr>
<td>{first_name}</td>
<td>{last_name}</td>
<td>{email}</td>
<td>{city}</td>
</tr>
{/exp:query}
Does anyone know why this error is occurring? Why would it be occurring on production but not locally?
Any help would be greatly appreciated!
Check to make sure the database in Production has the same structure as your Local environment.
Perform the following steps from phpMyAdmin or your favorite MySQL GUI client:
Select your ExpressionEngine database
Execute the following SQL Statements:
DESCRIBE exp_freeform_fields;
SELECT name FROM exp_freeform_fields;
Compare the results from your Local MySQL Database to your Production MySQL Database.
You probably got different database content on production and local systems so the statement fails on the production system producing an error.
You should try executing the statement in phpmyadmin or something like that to see if your sql statement is error-free and doesn't have any conflicts with naming.
Seems that your $query object has no valid connection. Control your username, password and database configuration.
Enable debugging in your config.php and database.php to see detailed error messages:
/system/expressionengine/config/config.php
$config['debug'] = '1';
/system/expressionengine/config/database.php
$db['expressionengine']['db_debug'] = TRUE;
It also wouldn't hurt to:
Verify your MySQL database credentials
Check Apache's and/or PHP's error_log
Hopefully, these steps will allow you to get more insight into your problem.

Empty database output in CI

I'm building a simple app and trying to test DB result output. But unfortunately all I'm getting is an array of size 0. Here's the controller code excerpt:
$data['query'] = $this->db->query('SELECT role_id, role_privilege FROM role');
$this->load->view('welcome_message', $data);
And a view code excerpt:
<?php
echo count($query->result_array())."<br/>";
foreach ($query->result() as $row){
echo $row->role_id . '<br/>';
echo $row->role_privilege . '<br/>';
}
echo 'Total result '.$query->num_rows();
?>
And what I get is next:
0
Total result
Running query from a command line gives a 2 rowed output. Can someone point out what i'm missing?
EDITED:
This issue is also discussed here .
EDITED:
Maybe some platform specific stuff (I really doubt that)? I'm running LAMP (php 5.3.2, mysql 5.1.37, apache 2.2.15).
EDITED:
This prints out a "Array ( )" string. My DB is 100% filled. I can say that for sure, because I did
INSERT INTO role(role_privilege) VALUES ('ROLE_MODERATOR');
INSERT INTO role(role_privilege) VALUES ('ROLE_USER');
and then checked it through a command line.
EDITED:
After I put this into my controller:
echo $this->db->last_query(); exit;
I get next output:
SELECT role_id, role_privilege FROM role
And that's exact sql query that I needed. Unfortunately results are o sized array.
Well, this here problem is basically not a CI related one, but strange thing is that CI couldn't track this error. Here's what was going on:
While installing php I haven't specified --with-mysql-socket parameter and it looks like php tried to use a /tmp/mysql.sock (default one) which obviously was not specified in my.cnf. So CI tried to bind to a nonexistent socket. Changing mysql params in a php.ini solved the problem.
Well, it sounds like your db access is set up properly because you're not getting an error. Which I think also means that the table exists. I know you said you ran that query from the command line, but are you certain you're accessing the same data set/server/table? No weird versioning or anything? It sounds like there aren't records in the role table. Sorry, just grasping at straws as your code looks right.
How about doing
SELECT * FROM role
and then doing a
print_r($query->result_array());
in your view? That should reveal column names at least so you know you're accessing the right data.
Try that and report back with any detail and hopefully it will supply some hints.

SQL debugging in large PHP app

I am using CodeCharge Studio to finish a large PHP application. This question isn't really CCS related, but a bit more general. I have a web form that is supposed to allow CRUD capabilities with a certain SQL Server table, but the Inserts keep failing without throwing any errors. What would be the best way to debug this?
When I'm having trouble with dynamically generated SQL queries, I typically echo out the query and try running that query on the console for the DB. Or alternatively, you could write a simple PHP function that writes out strings to a file, and that way you don't have to display the query directly on your page, but instead in a log file.
See what the actually query is and then try doing that query directly on the DB. Then you know whether it's a PHP issue or a DB issue.
Then go from there, depending on the outcome.
If the query looks OK, double check that the user running the query has insert rights to the database.
I've been caught out by that before.
You can monitor all sql queries in mysql as shown in this site, once you enable logging, run the query manually and see why its failing..this should be good starting point.
In addition to what's mentioned before, I can add my recent discovery:
trigger_error(print_r($your_var,1),E_USER_ERROR);
So you can output and debug your variable, even if it's a complex script with redirects, where simple echo would not help.
Dmitri.
You should try using FirePHP and log all the SQL to your Firebug:
An Example would be:
$sql = "SELECT * FROM table"
if (!mysql_query($sql)) {
// In un successfull log to FireBug
FB::error($data, "SQL error: ".mysql_error());
}
You can also implement the FB::error call from your own function, so you can later deactivate this behaviour modifying your function:
function log_error($data, $msg){
//dont forget to deactivate in case the application goes live!
FB::error($data, $msg);
}
if (!mysql_query($sql)) {
// In un successfull log to FireBug
log_error($data, "SQL error: ".mysql_error());
}
Most of the database connection classes in CodeCharge have a 'debug' flag which will automatically write all the page's database commands at the top of the page.
For example, in an old PHP project of mine, 'Common Files' the file 'db_mysql.php' (line 27):
public $Debug = 0; ## Set to 1 for debugging messages.
Change to '1' and publish that file. Load the web page. Change back and re-publish when done.
I've used this in CCS for PHP and ASP projects, and is likely in the other languages (not sure if or where to find in .NET projects).

Categories