5

How do I write:

$count = mysql_num_rows($result);
print "<h3>$count metal prices available</h3>";

to a file, index.php?

I've tried:

echo "$count = mysql_num_rows($result);
print "<h3>$count metal prices available</h3>";" > index.php

but I don't understand how to escape the double quotes that are in the input.

Would it be better to use something other than echo? I'd rather not rewrite the whole PHP script if possible (it's longer than the 2 lines given in the example!).

3 Answers 3

13

There would be several ways to do so:

 cat >index.php <<'EOT'
 $count = mysql_num_rows($result);
 print "<h3>$count metal prices available</h3>";
 EOT

or

 echo '$count = mysql_num_rows($result);
 print "<h3>$count metal prices available</h3>";' > index.php

or

 echo '$count = mysql_num_rows($result);' >index.php  # overwrites file if it already exists
 echo 'print "<h3>$count metal prices available</h3>";' >>index.php  # appends to file

there are much more possible ways - use this as a starting point for test things...

1
  • I especially like the first one. Thanks!
    – taranaki
    Feb 8, 2019 at 2:52
3

In bash, all you need to do is replace the outer quotes with single quotes:

echo '$count = mysql_num_rows($result);                                                                  
print "<h3>$count metal prices available</h3>";' > index.php

If you need to do more complicated stuff, you can echo multiple times using ">>" which appends instead of overwrites:

echo '$count = mysql_num_rows($result);' >> index.php
echo 'print "<h3>$count metal prices available</h3>";' >> index.php
0

My script to save multiline into a .csv file:

#! /bin/bash
while [ 1 ]
do
    sleep 1s
    str="\""$(date)"\""
    echo   ${str} >>333.csv
    
    # begin add next row
    echo ",\"" >>333.csv
    # append multiline result
    ps >>333.csv
    # end add next row
    echo "\"" >>333.csv
    
    # begin add next row
    echo ",\"" >>333.csv
    # append multiline result
    df -h >>333.csv
    # end add next row
    echo "\"" >>333.csv
    
    sed -i ":a;N;s/\"\n\,/\"\,/g;ta" ./333.csv
done
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 9, 2023 at 7:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .