通过curl将数据库数据发布到php

时间:2016-04-21 06:54:21

标签: php database post curl

我正在尝试创建一个读取数据库表的php文件,并通过curl将该表的行发布到php表单。

以下代码通过curl将表的第一行发布到php文件。它不会循环遍历表的所有行并逐步发布它们。

<?php

define('DB_HOST', 'localhost'); 
define('DB_NAME', 'dbname'); 
define('DB_USER','dbuser'); 
define('DB_PASSWORD','dbpass'); 
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); 
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); 


$result = mysql_query("SELECT name,contact,city FROM customers; ");

while ($row = mysql_fetch_assoc($result)) {


$parts = explode(" ", $row[name]);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);

$gmail = "@gmail.com";
$email = $firstname.$lastname.$gmail ;

$particip = "aaa" ;


$fields = array(
    'fname' => rawurlencode($firstname),
    'lname' => rawurlencode($lastname),
    'mbl' => rawurlencode($row[contact]),
    'email' => rawurlencode($email),
    'city' => rawurlencode($row[city]),
    'e' => rawurlencode($particip)  
);




//extract data from the post
//set POST variables


$url = 'http://example.com/form.php';


//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result1 = curl_exec($ch);

echo $result1;

//close connection
curl_close($ch);



}
?>

更新:这些值正在发布到表单php文件中。从顶行到底行。但只获取数据库条目中的第一行。

有没有办法在发布第二行数据库数据之前刷新$ url?

1 个答案:

答案 0 :(得分:0)

$fields[] = array(
    'fname' => rawurlencode($firstname),
    'lname' => rawurlencode($lastname),
    'mbl' => rawurlencode($row[contact]),
    'email' => rawurlencode($email),
    'city' => rawurlencode($row[city]),
    'e' => rawurlencode($particip)  
);

试试这种方式