Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
uh zip zoom
May 28, 2003

Sensitive Thugs Need Hugs

Alex007 posted:

But don't save images into a database. Databases are for data, the filesystem is for files.

this may be the dumbest loving question ever, but you mean don't save image files into a database, right? Or do you mean "don't save image data like file names and alternate text, etc. into a database"?

Sorry if this is a waste of Internet, but I'm trying to teach myself object-oriented php for developing data driven sites. That said, are there any good books on this that I could look at (to supplement my lurking and poo poo posting ITT)?

uh zip zoom fucked around with this message at 20:57 on Aug 10, 2010

Adbot
ADBOT LOVES YOU

KuruMonkey
Jul 23, 2004

uh zip zoom posted:

this may be the dumbest loving question ever, but you mean don't save image files into a database, right? Or do you mean "don't save image data like file names and alternate text, etc. into a database"?

Don't save the actual image data itself in a db. Save the image as a file, store the path to that file in the db.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Alex007 posted:

Assuming $tmp is your image resource:

php:
<?
    ob_start();
    imagejpeg($tmp, NULL, 100);  break; // best quality

    $image_text = ob_get_contents();
    ob_end_clean();
?>
But don't save images into a database. Databases are for data, the filesystem is for files.

imagejpeg with a NULL as the second parameter will displayooooooooooooh I see. ... That's pretty smart. :eng99:

As for saving the images to the database, I generally agree, but in this case we're probably doing worse things with image storage than that. (See a page or two ago where I admitted to storing image data in a session variable)

N.Z.'s Champion
Jun 8, 2003

Yam Slacker

Munkeymon posted:

Well, if he doesn't want to keep the array, he can use a different function to extract the value: [...]
But, yeah, PHP Sucks Exhibit n+1
There's also php's extract() which will dump array variables into the current context as individual variables. It's like unpacking array items with ** in Python.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

KuruMonkey posted:

Don't save the actual image data itself in a db. Save the image as a file, store the path to that file in the db.

this this this this this this this

gibbed
Apr 10, 2006

DholmbladRU posted:

I am attempting to create an update profile page on thie website, however I am having some trouble keeping multiple forms on the same page from affecting each other.

here is some psudo code for what I want to do
code:


execute if form1 was "submitted" {
some code		
}

execute if form2 was "submitted" {
    some code
	}
By searching online someone sugessted you name the forms, and then use the $_REQUEST to see if they are set.

php:
<?
    
if (isset($_REQUEST['submit2'])) { 
    if($Password1 = $Password2) 
        {
            code
        
            }
            
        }
?>
Everyone else seems to have missed this (and duplicated it in their code edits? :v:) but please learn your operators.

(I'm assuming this is an actual mistake made in your original code)

Lamb-Blaster 4000
Sep 20, 2007

I just installed a php 5.2.14 and set the extension_dir to c:\PHP\ext, but when I run a page that calls phpinfo it says extension_dir is still C:\php5

I don't have any other ini files except the one that's in the php folder, I even copied that one to the same directory where the php file is that calls phpinfo, and still no luck.

more info Im running IIS 6 and the application mapping for the .php extension is to php5isapi.dll

I tried renaming php.ini to php5.ini but it's still using the default values

Lamb-Blaster 4000 fucked around with this message at 22:47 on Aug 13, 2010

mik
Oct 16, 2003
oh
I'm sick and tired of this. Can someone please tell me why I keep getting a Fatal memory error when I run this script?

I have a function that scrapes data from Yahoo Finance and puts the data into a table in my database. Because I'm grabbing almost 4000 stocks (i.e the function runs 4000 times) in order to avoid timeouts I have the script do 100 at a time, then the page reloads, the script gets the next 100 and so on.

However, nine times out of ten, at some point during the procedure I get the following error:

code:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4194304 bytes) in
 /home/username/domains/domain.net/public_html/opg/functions.php on line 122
Sometimes it's large like 4mb above and sometimes it's just trying to allocate 71 bytes or something tiny.

The function itself is as follows:

php:
<?

for(i=0;$i<100;$i++){

      getyahootickerdata($tickers[$i],"2010-01-01","2010-08-13");

}


// when this completes the page reloads and loops through 100 more tickers




function getyahootickerdata($ticker,$startdate,$enddate){

    list($start_year,$start_month,$start_day)    =    split("-",$startdate);
    list($end_year,$end_month,$end_day)            =    split("-",$enddate);

    $yurl        =    "http://ichart.finance.yahoo.com/table.csv?s=".trim($ticker)."&a=".($start_month-
1)."&b=".$start_day."&c=".$start_year."&d=".($end_month-
1)."&e=".$end_day."&f=".$end_year."&g=d&ignore=.csv";

    if(url_exists($yurl)){

        $fname             = fopen($yurl,'r');

        while(($csv_line = @fgetcsv($fname,500,",")) !== FALSE){
                $date_array[]    =    $csv_line[0];
                $open_array[]    =    $csv_line[1];
                $close_array[]    =    $csv_line[4];
                $volume_array[]    =    $csv_line[5];
                $adj_close_array[]    =    $csv_line[6];
        }
        fclose($fname);

        $csv_line_count    =    count($date_array);
    
        for($lc=$csv_line_count-1;$lc>0;$lc--){
            $gap    =    ($open_array[$lc]/$adj_close_array[$lc+1]-1);
            $chg    =    ($close_array[$lc]/$open_array[$lc]-1);
            $clscls    =    ($adj_close_array[$lc]/$adj_close_array[$lc+1]-1);    
        
            $input_array[]    =
    "(NULL,'".$ticker."','".$date_array[$lc]."','".$open_array[$lc]."','".$close_array[$lc]."','".$gap."',
'".$volume_array[$lc]."','".$chg."','".$clscls."')";
        
        }
        
        
        dbconnect();
        $query    =    'INSERT INTO yahoo_data VALUES'.implode(',',$input_array);
        mysql_query($query);        
        dbclose();
        
        $csv_line = null;
        $input_array = null;
        $date_array = null;
        $open_array = null;
        $close_array = null;
        $volume_array = null;
        $adj_close_array = null;    
        
        
        
        unset($csv_line);
        unset($input_array);
        unset($date_array);
        unset($open_array);
        unset($close_array);
        unset($volume_array);
           unset($adj_close_array);
                
    }    

}

?>
The error, when it happens (as I said 90% of the time) always happens on one of the following lines:

php:
<?
                $date_array[]    =    $csv_line[0];
                $open_array[]    =    $csv_line[1];
                $close_array[]    =    $csv_line[4];
                $volume_array[]    =    $csv_line[5];
                $adj_close_array[]    =    $csv_line[6];
?>
I've played with the line length parameter of fgetcsv, I've tried only doing 5 tickers at once, but i keep getting out of memory errors. I'm using a fast host (https://www.medialayer.net) so I don't suspect the server itself is overloaded by other people, it happens at all times of the day.

The reason I populate the arrays then loop through them to put the info in the database is because the .csv file i read the data from is in descending date order and I need my table to be in ascending order. I could do some wizardry and flip my table after all the data is in, but the script still shouldn't be running out of memory seeing as how the files that are read are only 20KB. Sometimes the error happens early on like stock 400, sometimes it dies almost at the end like stock 3500.

Where am I leaking memory? Feel free to mock my code.

epswing
Nov 4, 2003

Soiled Meat

mik posted:

The reason I populate the arrays then loop through them to put the info in the database is because the .csv file i read the data from is in descending date order and I need my table to be in ascending order. I could do some wizardry and flip my table after all the data is in

What do you care what order the data hits the db in? Number it appropriately as it goes in, and use ORDER BY when pulling it out later. Rather than using a php script to buffer the whole output.

Alex007
Jul 8, 2004

Lamb-Blaster 4000 posted:

I just installed a php 5.2.14 and set the extension_dir to c:\PHP\ext, but when I run a page that calls phpinfo it says extension_dir is still C:\php5

I don't have any other ini files except the one that's in the php folder, I even copied that one to the same directory where the php file is that calls phpinfo, and still no luck.

more info Im running IIS 6 and the application mapping for the .php extension is to php5isapi.dll

I tried renaming php.ini to php5.ini but it's still using the default values

phpinfo() shoul tell you where it it loading php.ini from. I've seen it try C:\php (or C:\program files\php) and C:\windows. Try naming it php-isapi.ini, php-cgi.ini or pnp-fcgi.ini. When php DOES load an ini, phpinfo() tell you which one it loaded.

I usually run php5 trough fastcgi, so in myu case php-fcgi.ini is the one it looks for.

Masked Pumpkin
May 10, 2008
It's not exactly a php question per se, but I'm trying to find the best way to address this in PHP:

I'm doing up a program to handle scheduling for a setup managing adverts. This means that an entire day has to be broken up into 10 second segments, with long, feature length items and then some short adverts - with the option to move these around if necessary. At first I considered setting up the appropriate table with an entry for each 10 second gap (longer features could span multiple rows), but discarded this a it led to massive tables and slow db access times. I then considered simply using a text field, writing the times and items to play into there, and processing the information accordingly when it came in or out.

I then ran into the problem of displaying this information nicely on the scheduling page - pretty much any way I do it, that many segments ends up scrolling across the page, even at a high resolution. I'd use GD to generate a nice image representing the data, but then moving items around becomes problematic.

Ultimately, I can make it all work with tables and forms, but I can't help but feel I'm missing some better way of doing this, and am at a loss. Any ideas?

Fehler
Dec 14, 2004

.
Can anybody recommend me a wiki application written in PHP other than MediaWiki?

Pablo Bluth
Sep 7, 2007

I've made a huge mistake.
I've only deployed it for smallish-scale use in an intranet situation, but I like dokuwiki.

Fehler
Dec 14, 2004

.

Pablo Bluth posted:

I've only deployed it for smallish-scale use in an intranet situation, but I like dokuwiki.
That looks great, thanks!

N.Z.'s Champion
Jun 8, 2003

Yam Slacker

Masked Pumpkin posted:

At first I considered setting up the appropriate table with an entry for each 10 second gap (longer features could span multiple rows), but discarded this a it led to massive tables and slow db access times. I then considered simply using a text field, writing the times and items to play into there, and processing the information accordingly when it came in or out.
Well if you're displaying one day then 10 second segments could be 6*60*24=8640 rows so how do you expect to present that in a user interface? It's almost like you want to deal with groups of information at different resolutions of detail.

As far as storing events (timestamp+duration) in a database then I've used Postgres 8.4 with timestamps and intervals. You can then select an event and join its timestamp against a dynamically generated table of dates at an arbitrary resolution by using generate_series().

I don't know if this is the most efficient way of doing it but it's fast enough for me.

Masked Pumpkin
May 10, 2008

N.Z.'s Champion posted:

Well if you're displaying one day then 10 second segments could be 6*60*24=8640 rows so how do you expect to present that in a user interface? It's almost like you want to deal with groups of information at different resolutions of detail.

As far as storing events (timestamp+duration) in a database then I've used Postgres 8.4 with timestamps and intervals. You can then select an event and join its timestamp against a dynamically generated table of dates at an arbitrary resolution by using generate_series().

I don't know if this is the most efficient way of doing it but it's fast enough for me.

Those are some great points - Breaking down the times into smaller sections (and hell, using GD to give birds eye view of larger segments of data) would work well as although it might require more page refreshes, these could at least be done reasonably quickly.

I'm using MySQL, but it appears that it also allows date calculations as you've described, which would be more sensible than trying to run the same processes through PHP - though I will have to study up on it, as it's not something I've ever considered doing with a database before.

Thank you for your help!

Lamb-Blaster 4000
Sep 20, 2007

Pablo Bluth posted:

I've only deployed it for smallish-scale use in an intranet situation, but I like dokuwiki.

someone here recommended dokuwiki to me a couple weeks ago, definitely recommend.

Alex007 posted:

phpinfo() shoul tell you where it it loading php.ini from. I've seen it try C:\php (or C:\program files\php) and C:\windows. Try naming it php-isapi.ini, php-cgi.ini or pnp-fcgi.ini. When php DOES load an ini, phpinfo() tell you which one it loaded.

I usually run php5 trough fastcgi, so in myu case php-fcgi.ini is the one it looks for.

It's trying the windows dir, I'm running ISAPI, so I tried renaming it php-isapi, php5 even php-cgi, but it's still looking in windows. I put a copy of php.ini in the windows dir, but it's still loading all the defaults and telling me it's not loading an ini file.

I even put an ini_set('extension_dir','C:/PHP/ext'); before the phpinfo call, but it seems to be ignoring that too.

Solved: apparently php run in ISAPI only loads its ini file when w3wp.exe is run, so recycling its application pool in IIS fixed the problem (http://forums.iis.net/t/1134052.aspx)

Lamb-Blaster 4000 fucked around with this message at 18:19 on Aug 16, 2010

DholmbladRU
May 4, 2006
At the beginning of most pages of a php site I am creating I check for a session variable. After this is checked the page decides which header to use.


php:
<?
session_start();
if (isset($_SESSION['this'])) {
require './securepage.html';
}
else {
require './nonsecure.html';

}
?>
I would like to redirect to the index, or a page asking a user to login(sets 'this') if they attempt to view a page when not logged in.

Lamb-Blaster 4000
Sep 20, 2007

DholmbladRU posted:

At the beginning of most pages of a php site I am creating I check for a session variable. After this is checked the page decides which header to use.


php:
<?
session_start();
if (isset($_SESSION['this'])) {
require './securepage.html';
}
else {
require './nonsecure.html';

}
?>
I would like to redirect to the index, or a page asking a user to login(sets 'this') if they attempt to view a page when not logged in.

header('Location: index.php');

Lamb-Blaster 4000 fucked around with this message at 18:20 on Aug 16, 2010

DholmbladRU
May 4, 2006
I have a page I am trying to display with information about a person. One of those fields is a 'class' identifier, so it could be A,B,C,D. Now when I output this I would like the list to be grouped by the classes. Right now this is what I am doing and it is unordered.


php:
<?
 while ($row=mysql_fetch_array($results)) 
                  { 
                     echo "<tr>";
                     echo "<td  WIDTH=200>", $row['name'], "</td>";
                     echo "<td  WIDTH=200>", $row['name2'], "</td>";
                     echo "<td  WIDTH=200>", $row['email'], "</td>";
                     echo "<td  WIDTH=200>", $row['Class'], "</td>"
                     echo "</tr>";
                  
                  }

?>
What is a good approach to this problem?

Lamb-Blaster 4000
Sep 20, 2007

DholmbladRU posted:

I have a page I am trying to display with information about a person. One of those fields is a 'class' identifier, so it could be A,B,C,D. Now when I output this I would like the list to be grouped by the classes. Right now this is what I am doing and it is unordered.


php:
<?
 while ($row=mysql_fetch_array($results)) 
                  { 
                     echo "<tr>";
                     echo "<td  WIDTH=200>", $row['name'], "</td>";
                     echo "<td  WIDTH=200>", $row['name2'], "</td>";
                     echo "<td  WIDTH=200>", $row['email'], "</td>";
                     echo "<td  WIDTH=200>", $row['Class'], "</td>"
                     echo "</tr>";
                  
                  }

?>
What is a good approach to this problem?

You could use GROUP BY in your sql select, then you dont have to bother with any logic in PHP.

So my PHP installation now knows where to look for my MySQL extensions, and the lines telling it to load them have been un commented, but PHP will only load mbstring, it ignores the mysql extensions :(

DholmbladRU
May 4, 2006
Should it be group by, or order by?

When I attempted group by with this select stament only one row for each 'class' was returned.

php:
<?
$SQLcmd = "SELECT * FROM $table group by Class"; ?>
However when changed to order by, all were displayed.

Lamb-Blaster 4000
Sep 20, 2007

DholmbladRU posted:

Should it be group by, or order by?

When I attempted group by with this select stament only one row for each 'class' was returned.

php:
<?
$SQLcmd = "SELECT * FROM $table group by Class"; ?>
However when changed to order by, all were displayed.

yeah order by is fine as well

Fehler
Dec 14, 2004

.
Has to be ORDER BY, GROUP BY will only output one row per class.

DoctorScurvy
Nov 11, 2005
More of a passing curiosity, really

DholmbladRU posted:

I have a page I am trying to display with information about a person. One of those fields is a 'class' identifier, so it could be A,B,C,D. Now when I output this I would like the list to be grouped by the classes. Right now this is what I am doing and it is unordered.
Here is my inelegant approach to this sort of thing:
php:
<?
$lastclass = '';
$SQLcmd = "SELECT * FROM $table order by Class asc";
$results = mysql_query($SQLcmd) OR die(mysql_error());

while ($row=mysql_fetch_array($results)) { 
    if ($lastclass != $row['Class']) {
        echo "<tr><th colspan=4>".$row['Class']."</th></tr>";
        $lastclass = $row['Class'];
    }
    echo "<tr>";
    echo "<td  WIDTH=200>", $row['name'], "</td>";
    echo "<td  WIDTH=200>", $row['name2'], "</td>";
    echo "<td  WIDTH=200>", $row['email'], "</td>";
    echo "<td  WIDTH=200>", $row['Class'], "</td>"
    echo "</tr>";           
}
?>

DoctorScurvy fucked around with this message at 08:57 on Aug 17, 2010

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



I got bored the other day and decided to test some things I had read about string handling in PHP.

I made this in order to do that. (linked because it's kind of long)

Now I'm wondering how valid are these tests are because I'm getting some odd results - on PHP 5.2.5 on Windows (using Apache), this king of loop:
php:
<?
for($i = 0; $i < count($array); ++$i){
   $something .= $array[$i];
}
?>
is consistently about 100 times faster than this:
php:
<?
$count = count($array);
for($i = 0; $i < $count; ++$i){
   //same as above
}
?>
:confused:

KuruMonkey
Jul 23, 2004

Munkeymon posted:

Now I'm wondering how valid are these tests are because I'm getting some odd results - on PHP 5.2.5 on Windows (using Apache), this king of loop:
php:
<?
for($i = 0; $i < count($array); ++$i){
   $something .= $array[$i];
}
?>
is consistently about 100 times faster than this:
php:
<?
$count = count($array);
for($i = 0; $i < $count; ++$i){
   //same as above
}
?>
:confused:

I've run similar, simpler, tests - and got more ... expected results:
php:
<?
   function timer($k)
    {
        static $keys = array();
 
        $init = microtime(TRUE);    // store execution time of this call immediately
 
        if(!array_key_exists($k, $keys))
        {
            $keys[$k] = $init;
            return;
        }
        else
        {
            $exec = ($init - $keys[$k]) * 1000;
            unset($keys[$k]);
            return $exec;
        }
    }

    define('COUNT', 300000);
    
    echo "Loop Performance Test<br>Arbitrarily large numbers of iterations<br>";

    $a = array();
    for($i = 0; $i < COUNT; $i++)
    {
        $a[]= str_repeat(chr(rand(32, 126)), rand(1, 100));
    }
    
    // for / constant
    timer('time');
    for($i = 0; $i < COUNT; $i++)
    {
        $s = $a[$i];
    }
    $elapsed = timer('time');
    echo 'Limit is a constant, for loop: '.$elapsed.'<br>';
    
    // for / limit
    timer('test');
    $limit = count($a);
    for($i=0; $i<$limit; $i++)
    {
        $s = $a[$i];
    }
    $elapsed = timer('test');
    echo 'Limit is a variable calculated outside for loop: '.$elapsed.'<br>';
    
    // for / loop / non-optimal
    timer('test');
    for($i=0; $i<count($a); $i++)
    {
        $s = $a[$i];
    }
    $elapsed = timer('test');
    echo 'Limit is a variable calculated inside for loop: '.$elapsed.'<br>';    
    
    timer('test');
    foreach($a as $i)
    {
        $s = $i;
    }
    $elapsed = timer('test');
    echo 'foreach loop: '.$elapsed.'<br>';
?>
example results:
code:
Loop Performance Test
Arbitrarily large numbers of iterations
Limit is a constant, for loop: 104.24900054932
Limit is a variable calculated outside for loop: 83.511114120483
Limit is a variable calculated inside for loop: 165.73977470398
foreach loop: 66.704034805298
Notes:

obviously I'm not bothering to measure the memory usage, and I'm probably straight up using less memory than you. But my results (1and1 shared linux server) are, as I said, more what you would expect - unless the windows php interpreter is optimising that particular construction (possible?)

Constants are slow?!?

foreach is fast; if you really have to loop through 300k element arrays, use foreach + break

DholmbladRU
May 4, 2006
Been working on this site in my free time, I am by no means good at php/html as this is the first site I have built. What is a good way to approach the difference in browser/screen resolutions that a page may be viewed in. For example when I view this page on my laptop there is a scroll bar on the bottom.

btw I am using absolute positioning, which may make this more difficult.


https://php.radford.edu/~sigmapi/index.php

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



KuruMonkey posted:

foreach is fast; if you really have to loop through 300k element arrays, use foreach + break

I'm doing the tests primarily because it's a very common idiom at my company to do poo poo like this:

php:
<?
while($something == true){
  //20 or so lines of
  $buffer .= "blah blah ".$whatever." the end\n";
  //lather, rinse, repeat 500 times - maybe 10000+
}

echo $buffer; //$buffer can be pretty long at this point
?>
Usually I try to replace it with an array or array of arrays, then a foreach and/or implode, but I wanted to make sure I wasn't creating a new problem based on bad information from random blogs. Of course, I try to get the data out of PHP and into Apache's buffer as quickly as possible.

The same tests on my Dreamhost account have the pre-counted loop just 50 times slower than the naive loop. I suppose I could dig through the byte code - woo

Munkeymon fucked around with this message at 02:17 on Aug 17, 2010

KuruMonkey
Jul 23, 2004

Munkeymon posted:

I'm doing the tests primarily because it's a very common idiom at my company to do poo poo like this:

Given that it looked like your code was building some large strings in its tests; have you tried running the tests in isolation, or even just in the opposite order?

I mean; if you want to test the faster way to create longish strings in a large loop, you first test the faster loop method in isolation (doing something constant and simple that doesn't chew up memory), then the faster concatenation method in isolation (by using the same loop method throughout)

I think you'll get a result of foreach + implode being best.

i.e.
php:
<?
function format_huge_data($data, $formatter, $pre, $post, $between)
{
  $output = array();
  foreach($data as $datum)
    $output[] = $formatter($datum);
  return $pre . implode($between, $output) . $post;
}
?>
Note: in which case its worth testing array_map() as well?

Alex007
Jul 8, 2004

Anyone can recommend an S3 library for PHP ? There's two dozens of them out there and it is hard to pick which one is the correct one to use in a big project, they all look like some basic proof of concept not maintained anymore.

The project runs PHP 5.3.3 on IIS 7. I don't need advanced features like user creation or manage access rights, all I really need is to store backups of files uploaded by my users.

Thanks !

MrMoo
Sep 14, 2000

This one, http://undesigned.org.za/2007/10/22/amazon-s3-php-class

Alex007
Jul 8, 2004


DOH, forgot to say I need reduced redundancy storage. That one doesn't support it. It would also be a nice indication that the library is still actively maintained.

I'll look into it to see if I can add it myself.

EDIT: Yeah it was easy to add RRS support, that library will be perfect. Thanks !

Alex007 fucked around with this message at 13:41 on Aug 17, 2010

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Hungarian notation in PHP: The best idea, or the bestest idea? (or probably not) New work has me doing it, and after a while it becomes second nature, but I'm pretty sure it's not actually useful. At the very least, it's now given me a standard $b for a throwaway boolean, stands out a little more than my previous $x. :v:

Golbez fucked around with this message at 14:32 on Aug 17, 2010

Flamadiddle
May 9, 2004

Stupid question, I'm sure, but I'm calling an SQL stored procedure in PHP using sqlsrv_query. I'm providing an out parameter which receives a string, but it seems I have to initialise it in order to get anything sensible out. The problem is that the returned value is truncated to the length of the string I use to initialise the variable. Is there any way to avoid this or will I just have to initialise the variable as
code:
$var = "                                    ";
etc...

My PHP is rusty so I wasn't sure if there was a way to initialise a string as an empty string of a given length...

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
I don't know how sqlsrv_query works, but you could use str_pad.
code:
$var = str_pad('', 1000);
Would create a string with 1000 spaces.

KuruMonkey
Jul 23, 2004
php:
<?
$s = str_repeat($what, $how_many)
?>

Flamadiddle
May 9, 2004

Golbez posted:

I don't know how sqlsrv_query works, but you could use str_pad.
code:
$var = str_pad('', 1000);
Would create a string with 1000 spaces.

Awesome. Thanks. Should've thought about padding. I'm sure there's a better way to initialise the parameter, but I'm just prototyping right now.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Flamadiddle posted:

Awesome. Thanks. Should've thought about padding. I'm sure there's a better way to initialise the parameter, but I'm just prototyping right now.

KuruMonkey's str_repeat is probably an ever-so-slightly 'purer' solution. But this sounds like a very strange error on sqlsrv_query's part.

Adbot
ADBOT LOVES YOU

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Hm. Just wondering, is it necessary to run a mysql_num_rows > 0 before doing a while $x = mysql_fetch_assoc? I suppose it might be cleaner, but if zero rows were returned, then the while wouldn't even attempt to run it, right?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply