Frage

I want to create a temp database in MySQL. The row's content are taken from an external page which I use PHPQuery to parse. The number of times for for loop runs is also taken from that page, running the amount of times that there are elements present on the page.

The following code barely works. I assumed it would run the code $number of times, where $i increases by one each time it runs. This way, it would insert $new[0], $new[1], $new[2], etc. into the database. The problem is, it only inserts the last instance.

Say $number is 11, it will only insert $new[11] into the database.

$server = "localhost";
$username = "***";
$password = "***";
$database = "***";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$number = pq('.trafficbriefs:contains(\'SCHOOLS\')') -> parent() -> find('.maintext') -> length();
for ($i = 0; $i < $number; $i++) {
    $test = pq('.trafficbriefs:contains(\'SCHOOLS\')') -> parent() -> find('.maintext') -> eq($i) -> text();
    $new[$i] = $test;
    $sql = "INSERT INTO Temp (School) ";
    $sql .= "VALUES ('$new[$i]')";
}

if (!mysql_query($sql, $con)) {
        die('Error: ' . mysql_error());
    } else {
        echo "Added to database.";
    }

mysql_close($con);
War es hilfreich?

Lösung

Whatever does the mysql_query also needs to be inside that loop.

Andere Tipps

I don't know if thats what you need but this code is going to build a query first, then execute it once. Yhis query is going to insert everything you wanted to insert in one go. This is going to be a lot faster if the $number is big.

$server = "localhost";
$username = "***";
$password = "***";
$database = "***";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$number = pq('.trafficbriefs:contains(\'SCHOOLS\')')->parent()->find('.maintext')->length();
$queryParts = array();
for ($i = 0; $i < $number; $i++) {
    $test = pq('.trafficbriefs:contains(\'SCHOOLS\')')->parent()->find('.maintext')->eq($i)->text();
    $queryParts[] = '("' . $test . '")';
}
if (empty($queryParts)) {
    throw new Exception('Nothing to insert');
}
$query = 'INSERT INTO Temp (School) VALUES ' . implode(', ', $queryParts);
if (!mysql_query($query, $con)) {
    die('Error: ' . mysql_error());
} else {
    echo "Added to database.";
}
mysql_close($con);

Try this:

$sql = "";
for ($i = 0; $i < $number; $i++) 
{
    $test = pq('.trafficbriefs:contains(\'SCHOOLS\')') -> parent() -> find('.maintext') -> eq($i) -> text();
    $new[$i] = $test;
    $sql .= "INSERT INTO Temp (School) ";
    $sql .= "VALUES ('$new[$i]');";
}

Concatenates each statement and separates them with semi-colon

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top