I'm developing an android application that uses PHP and makes requests with Mysql. Initially I tested all the features on the local server to then migrate it to an online server, in this case, Hostinger.
One of my PHP files returns the value of an array correctly on the local server, however, when using the same PHP file on the online server with the same database, the array only responds to TRUE when I run echo.
I tried doing the echo of each line and it is working perfectly, just not being able to associate the values with the keys in the array.
$result= mysqli_query($connect, $sql);
while ($patients= $result->fetch_assoc()){
echo $patients['group']; //prints OK
echo $patients['exercise_name']; //prints OK
echo $patients['use_exercise']; //prints OK
$insert[] = array("group" => $patients['group'],
"name" => $patients['exercise_name'],
"use" => $pacientes['use_exercise']
);
}
echo json_encode($insert); //prints TRUE
My mysql output from $result:
+------------------------------------------+
| group exercise_name use_exercise |
+------------------------------------------+
| Knee Knee _1 1 |
| Knee Knee _2 1 |
| Knee Knee _3 0 |
| Knee Knee _4 0 |
| Knee Knee _5 0 |
| Shoulder Shoulder_1 1 |
| Shoulder Shoulder_2 0 |
| Shoulder Shoulder_3 0 |
| Shoulder Shoulder_4 0 |
| Shoulder Shoulder_5 0 |
| Ankle Ankle _1 1 |
| Ankle Ankle _2 0 |
| Ankle Ankle _3 0 |
+------------------------------------------+
The rest of the PHP code is really not relevant to this. I ended up getting this result from it. My only problem is passing everything to the array. I've tested with another PHP file and it printed how it was supposed to, so I don't know what is happening.
Related
I have one system (Symfony 5, symfony/messenger) sending data to another (Symfony 3.4, enqueue/enqueue-bundle 0.9) using a rabbitmq queue.
The data is used to create entities (stored in a MySql 8 database) that are executed within a transaction in case of a failure, to return the Database to the initial state.
My code is something like this (on the Symfony 3.4 side where the error is):
function runInsideTx(callable $fn)
{
$this->em->getConnection()->beginTransaction();
try {
$resp = $fn();
$this->em->flush();
$this->em->getConnection()->commit();
return $resp;
} catch (Exception $ex) {
$this->em->getConnection()->rollBack();
throw $ex;
}
}
And inside runInsideTx I have code like
$this->functions->runInsideTx(function () use ($message) {
$entity = new SomeEntity();
...
$this->em->persist($entity);
$this->em->flush();
})
Workers run inside a Docker container using supervisor:
[program:interop-manager_tasks-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /app/bin/console enqueue:transport:consume manager_tasks_processor manager_tasks_prod --message-limit=1 -vvv
autostart=true
autorestart=true
numprocs=2
redirect_stderr=true
stopwaitsecs=3600
stdout_logfile = /var/log/manager_tasks_worker_out.log
stderr_logfile = /var/log/manager_tasks_worker_err.log
user=application
environment=HOME="/home/application",USER="application"
Randomly the error General error: 2006 MySQL server has gone away occurs. Initially I had a MySql 5 Database and changed it to a MySql 8, which I am running inside a docker container with a single database.
Update
I have this error too:
Warning: Error while sending QUERY packet.
This happens sometimes. It could be that it sends the task to the queue three times and it fails the first two and the third it processes it without problems
I also added the following parameters when running the MySQl server:
command: --sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' --default-authentication-plugin=mysql_native_password --max-allowed-packet=1G --innodb_buffer_pool_size=512M --innodb_lock_wait_timeout=500
But the problem persists.
SHOW VARIABLES LIKE '%timeout%'
+-----------------------------------+----------+
| Variable_name | Value |
+-----------------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| have_statement_timeout | YES |
| innodb_flush_log_at_timeout | 1 |
| innodb_lock_wait_timeout | 500 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 28800 |
| lock_wait_timeout | 31536000 |
| mysqlx_connect_timeout | 30 |
| mysqlx_idle_worker_thread_timeout | 60 |
| mysqlx_interactive_timeout | 28800 |
| mysqlx_port_open_timeout | 0 |
| mysqlx_read_timeout | 30 |
| mysqlx_wait_timeout | 28800 |
| mysqlx_write_timeout | 60 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| replica_net_timeout | 60 |
| rpl_stop_replica_timeout | 31536000 |
| rpl_stop_slave_timeout | 31536000 |
| slave_net_timeout | 60 |
| wait_timeout | 28800 |
+-----------------------------------+----------+
This is my first time using Box/Spout library. I am using WAMP server.
My question is the following:
require_once('./spout-master/src/Spout/Autoloader/autoload.php');
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$filePath = 'test.xlsx';
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($filePath);
[X]
$writer->addRow(['a'], $style);
$writer->close();
(1)
When I am running above code, I get the following error message:
Warning: rmdir(C:\WINDOWS\TEMP/xlsx560f58d588ceb): Permission denied in
C:\wamp\www\1300.revenue.com.my\public_html\spoutmaster\src\Spout\Common\Helper\FileSystemHelper.php on line 113
What is the errors means and how should I modify it to prevent this error message appeared?
(2) I want to make expected output like below:
But I didn't know how to write it on [X] part. How to write it in order to get the expected output?
It looks like the default temp folder used to generate the XLSX file cannot be deleted. You can verify it by checking the permissions on C:\WINDOWS\TEMP/xlsx560f58d588ceb.
To solve this issue, you can either manually fix the permissions on the temp folder (C:\WINDOWS\TEMP) or use another temporary folder, as specified here: https://github.com/box/spout#using-custom-temporary-folder
Regarding 2), there is no straightforward way to do this whith Spout. Spout does not support merging cells. The only thing you can do is:
| 1 | 2 | | 3 | |
|---|---|---|---|---|
| | A | B | A | B |
|---|---|---|---|---|
Or alternatively (if that makes more sense):
| 1 | 2 | 2 | 3 | 3 |
|---|---|---|---|---|
| 1 | A | B | A | B |
|---|---|---|---|---|
Either way, you'll have to format the rows as shown above: [[1,2,'',3',''], ['', 'A','B','A','B']] or [[1,2,2,3,3], [1, 'A','B','A','B']]
I have the following code snippet in my file:-
session_start();
$_SESSION['fromPanel'] = "abcd";
<form method="post" action="/m/xyz.php">
<div class="text inputcaption"><b><?= _("Email")?></b></div>
<input type="email" name="username" value="<?=$objMobile->GetEmail()?>">
</div>
</form>
When the file xyz.php is called on post request, the $_SESSION array is coming empty. Please note session_start(); was given in xyz.php before printing the session array. Why is the session array getting empty by itself.
Code for xyz.php:
<?php
session_start();
print "<pre>";
print_r($_SESSION);
print "<post>";
?>
Please find the session settings obtained through phpinfo();
|---------------------------------|---------------------|---------------------|
| Session Support | enabled | |
| Registered | save handlers | files user |
| Registered | serializer handlers | php php_binary wddx |
| | | |
|---------------------------------|---------------------|---------------------|
| Directive | Local Value | Master Value |
|---------------------------------|---------------------|---------------------|
| session.auto_start | Off | Off |
| session.bug_compat_42 | On | On |
| session.bug_compat_warn | On | On |
| session.cache_expire | 180 | 180 |
| session.cache_limiter | nocache | nocache |
| session.cookie_domain | no value | no value |
| session.cookie_httponly | Off | Off |
| session.cookie_lifetime | 0 | 0 |
| session.cookie_path | / | / |
| session.cookie_secure | Off | Off |
| session.entropy_file | no value | no value |
| session.entropy_length | 0 | 0 |
| session.gc_divisor | 100 | 100 |
| session.gc_maxlifetime | 1440 | 1440 |
| session.gc_probability | 1 | 1 |
| session.hash_bits_per_character | 4 | 4 |
| session.hash_function | 0 | 0 |
| session.name | PHPSESSID | PHPSESSID |
| session.referer_check | no value | no value |
| session.save_handler | files | files |
| session.save_path | C:\Windows\Temp | C:\Windows\Temp |
| session.serialize_handler | php | php |
| session.use_cookies | On | On |
| session.use_only_cookies | Off | Off |
| session.use_trans_sid | 0 | 0 |
|---------------------------------|---------------------|---------------------|
On enabling error_reporting, following warnings were seen:
Warning: Unknown: open(C:\Windows\Temp\sess_1037ca26d3ebb62017eddc9cbfb107e2, O_RDWR) failed: Invalid argument (22) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (C:\Windows\Temp) in Unknown on line 0
I converted your snippet to working code and it runs like a charm.
Please provide a complete non-working example so we can help you.
a.php:
<?php
session_start();
$_SESSION['fromPanel'] = "abcd";
?>
<form method="post" action="./b.php">
<input type="email" name="username" value="john#example.com">
</form>
b.php:
<?php
session_start();
var_dump( $_SESSION['fromPanel'] );
var_dump( $_POST['username'] );
echo 'back to form';
result output after sending the form (with enter in input):
string 'abcd' (length=4)
string 'john#example.com' (length=16)
back to form
N.B: Use <label for="id-of-form">caption</label> instead of <div class="text inputcaption"></div>
More things to check:
Does the browser you are using accept cookies?
Clear cache and cookies, call session_regenerate_id() after session_start() to make sure it's not some old testing stuff that gives you trouble.
Is the session.save_path set and writeable? Check your phpinfo(); output.
Is xyz.php on the same domain? Cookies not allowed crosss domain.
Post your session.xyz settings.
Is this your own server? Try it on a hosted webspace or vice versa.
make sure there is no whitespace before the session_start() call.
call error_reporting(E_ALL) first thing.
make your example publicly available so others can check, too.
Go and have a beer. It will work next week. ;)
If you are including a common file in all the views like header.php or common.php just write session_start() at the top.
Ok, I have such script
#!/bin/bash
keyOrPass=$1
intercom=$2
flat=$3
number=$4
mysql -ulogin -ppass db_name -e "select cli.codeGuestEmail, cli.codePrivateEmail, cliKey.rf_id, cliKey.emailNotification from mbus_clients as cli join mbusClientKeys as cliKey on cliKey.id_client=cli.id WHERE cli.flat=${flat} and cli.domophone=${intercom};";
php -q sendNotifications.php
It works fine, but I should pass some result fields from select into php arguments. Any ideas how to do it?
OUTPUT:
+----------------+------------------+------------+-------------------+
| codeGuestEmail | codePrivateEmail | rf_id | emailNotification |
+----------------+------------------+------------+-------------------+
| 1 | 0 | 2774490192 | 0 |
| 1 | 0 | 2774490193 | 0 |
| 1 | 0 | 2774490194 | 0 |
| 1 | 0 | 2774490195 | 1 |
+----------------+------------------+------------+-------------------+
mysql is capable of generating output formatted differently. With the -B or --batch option, mysql produces the output with TAB as the column separator. The special characters in the fields are escaped (e.g. TAB is output as "\t") so you can use cut to extract fields.
Many times in cases like this it's helpful to use the -N or --skip-column-names option as well, in order to remove column names from the output.
I am trying to run a script through command prompt in PHP and trying to show the result in tabular form. But due to different character length of words I am not able to show the result properly align.
I want result like this
Book ISBN Department
Operating System 101 CS
C 102 CS
java 103 CS
Can anyone please help me to get this output like this in php on console.
Thanks in advance
If you don't want (or not allowed for some reason) to use libraries, you can use standard php printf / sprintf functions.
The problem with them that if you have values with variable and non-limited width, then you will have to decide if long values will be truncated or break table's layout.
First case:
// fixed width
$mask = "|%5.5s |%-30.30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value the end of which will be cut off');
The output is
| Num |Title | x |
| 1 |A value that fits the cell | x |
| 2 |A too long value the end of wh | x |
Second case:
// only min-width of cells is set
$mask = "|%5s |%-30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value that will brake the table');
And here we get
| Num |Title | x |
| 1 |A value that fits the cell | x |
| 2 |A too long value that will brake the table | x |
If neither of that satisfies your needs and you really need a table with flowing width columns, than you have to calculate maximum width of values in each column. But that is how PEAR::Console_Table exactly works.
You can use PEAR::Console_Table:
Console_Table helps you to display tabular data on a
terminal/shell/console.
Example:
require_once 'Console/Table.php';
$tbl = new Console_Table();
$tbl->setHeaders(array('Language', 'Year'));
$tbl->addRow(array('PHP', 1994));
$tbl->addRow(array('C', 1970));
$tbl->addRow(array('C++', 1983));
echo $tbl->getTable();
Output:
+----------+------+
| Language | Year |
+----------+------+
| PHP | 1994 |
| C | 1970 |
| C++ | 1983 |
+----------+------+
Your best option is to use the Pear Package Console_Table ( http://pear.php.net/package/Console_Table/ ).
To use - on a console you need to install the pear package, running:
pear install Console_Table
this should download the package and install. You can then use a sample script such as:
require_once 'Console/Table.php';
$tbl = new Console_Table();
$tbl->setHeaders(
array('Language', 'Year')
);
$tbl->addRow(array('PHP', 1994));
$tbl->addRow(array('C', 1970));
$tbl->addRow(array('C++', 1983));
echo $tbl->getTable();
You could try the recent simple PHP library ConsoleTable if you don't want to use the standard PHP functions printf/sprintf or the pear package PEAR::Console_Table.
Example:
require_once 'ConsoleTable.php';
$table = new LucidFrame\Console\ConsoleTable();
$table
->addHeader('Language')
->addHeader('Year')
->addRow()
->addColumn('PHP')
->addColumn(1994)
->addRow()
->addColumn('C++')
->addColumn(1983)
->addRow()
->addColumn('C')
->addColumn(1970)
->display()
;
Output:
+----------+------+
| Language | Year |
+----------+------+
| PHP | 1994 |
| C++ | 1983 |
| C | 1970 |
+----------+------+
See more example usages at its github page.
Too old, but i went trough the same now and used str_pad, just set the lenght as the size of your column and thats it
regards.
The CLIFramework table generator helps you get the job done very easily and it supports text alignment, text color, background color, text wrapping, text overflow handling.. etc
Here is the tutorial: https://github.com/c9s/CLIFramework/wiki/Using-Table-Component
Sample code: https://github.com/c9s/CLIFramework/blob/master/example/table.php
use CLIFramework\Component\Table\Table;
$table = new Table;
$table->setHeaders([ 'Published Date', 'Title', 'Description' ]);
$table->addRow(array(
"September 16, 2014",
"Title",
"Description",
29.5
));
$table->addRow(array(
"November 4, 2014",
"Hooked: How to Build Habit-Forming Products",
["Why do some products capture widespread attention whil..."],
99,
));
echo $table->render();
Just in case someone wants to do that in PHP I posted a gist on Github
https://gist.github.com/redestructa/2a7691e7f3ae69ec5161220c99e2d1b3
simply call:
$output = $tablePrinter->printLinesIntoArray($items, ['title', 'chilProp2']);
you may need to adapt the code if you are using a php version older than 7.2
after that call echo or writeLine depending on your environment.