0
votes

I'm trying to convert a data from string to float and insert it to MYSQL database. $data variable is a string. Here's my SQL query:

$sql = "CREATE TABLE IF NOT EXISTS $table (
               id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
               stockcode VARCHAR(8) NOT NULL,
               lastprice FLOAT NOT NULL,
               open FLOAT NOT NULL,
               close FLOAT NOT NULL,
               low FLOAT NOT NULL,
               high FLOAT NOT NULL
           )";


$rows = $table->getElementsByTagName("tr");

$i = 0;
foreach ($rows as $row) {
    if ($i++ < 1) {
        continue;
    }
    $a = array();
    $cells = $row->getElementsByTagName('td');
    $i = 0;
    foreach ($cells as $cell) {
        if ($i++ < 1) {
            continue;
        }
        array_push($a, floatval($cell->nodeValue));
    }
    print_r($a);
    var_dump($a);
    echo "<hr/>";
    $sql = "INSERT INTO $table (stockcode, lastprice, open, close, low, high)
        VALUES ( '" . $data[0] . "', '" . $data[1] . "', '" . $data[4] . "',   '" . $data[7] . "', '" . $data[5] . "', '" . $data[6] . "')";

But it still gives me error : PHP Catchable fatal error: Object of class DOMElement could not be converted to string in /var/www/html/mysqlcon.php on line 79

1
show us the data array - Royal Bg
I guess you have to use something like floatval( $data[n]->nodeValue ), but if you edit question adding a var_dump of $data we can better help you. - fusion3k
Consider using PDO and bound tokens, rather than just inlining variables into your mysql statements. See php.net/manual/en/mysqlinfo.api.choosing.php - Tim Ogilvy
i tried using that but to no avail. var_dump outputs to float but when i tried inserting it to MYSQL it creates the error @fusion3k - Newboy11
Post more relevant code (your $data construction) - fusion3k

1 Answers

0
votes

You need to put the float number between two quotations

$sql = "INSERT INTO $table(stockcode, lastprice, open, close, low, high)
   VALUES ( '".$data[0]."', '".floatval($data[1])."', '".floatval($data[4])."', '".floatval($data[7])."', '".floatval($data[5])."', '".floatval($data[6])."')";

even it's a number should be between two quotations