My goal is to create a general template to be used to INSERT INTO testquiz (a MySQL table). This will be used for storing quiz results and user information (name and email are the only user input in the database) from quiz takers. I am new to PHP/MySQL and feel like I am just stumbling around.
My problem is that I am unable to get the $_POST values that are generated by the quiz to appear in the database. I know the values are being generated because they will display with a basic echo. There is a 'send to email' feature that works with the values that is working as well. I can get this code to work if I manually assign values to the $_POST array by uncommenting the first comment block.
What am I missing here?
Sidenote: I'll take security suggestions as well. Thank you.
Code below (user specific information omitted):
<?php
//disable magic quotes (PHP book says it's a good idea)
if (get_magic_quotes_gpc())
{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process))
{
foreach ($val as $k => $v)
{
unset($process[$key][$k]);
if (is_array($v))
{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
}
else
{
$process[$key][stripslashes($k)] = striplashes($v);
}
}
}
unset($process);
}
/* //Manually declare $_POST variables (can be disabled)
$_POST['v'] = '6.5.1';
$_POST['sp'] = 80;
$_POST['psp'] = 75;
$_POST['tp'] = 80;
$_POST['sn'] = 'user';
$_POST['se'] = 'abc123#fake.com';
$_POST['qt'] = 'Test Quiz';
*/
//Assign $_POST values to static variables???
$version = $_POST['v'];
$points = $_POST['sp'];
$passing_percent = $_POST['psp'];
$gained_score = $_POST['tp'];
$username = $_POST['sn'];
$email = $_POST['se'];
$quiz_title = $_POST['qt'];
//MySQL database connection PDO
try
{
$pdo = new PDO('mysql:host=localhost;dbname=quizresults', 'user', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
//Prepare input for database entry
try
{
$sql = $pdo->prepare("INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date) VALUES (:version, :points, :passing_percent, :gained_score, :username, :email, :quiz_title, CURDATE())");
$sql->execute(array(":version" => $version, ":points" => $points, ":passing_percent" => $passing_percent, ":gained_score" => $gained_score, ":username" => $username, ":email" => $email, ":quiz_title" => $quiz_title));
//echo for debugging purposes
echo $version . '<br />', $points . '<br />', $passing_percent . '<br />', $gained_score . '<br />', $username . '<br />', $email . '<br />', $quiz_title . '<br />', date(DATE_ATOM);
}
catch (PDOException $e)
{
$error = 'Error adding quiz results to database: ' . $e->getMessage();
include 'error.html.php';
exit();
}
//Calculate user score
$points_num = (int)$points;
$passing_num = ((int)$passing_percent)/100 * (int)$gained_score;
//Write results to a text file
$f = fopen("result.txt", "w") or die("Error opening file 'result.txt' for writing");
fwrite($f, "--------------------------\n");
fwrite($f, "User name: ".$username."\n");
fwrite($f, "User email: ".$email."\n");
fwrite($f, "Quiz title: ".$quiz_title."\n");
fwrite($f, "Points awarded: ".$points."\n");
fwrite($f, "Total score: ".$gained_score."\n");
fwrite($f, "Passing score: ".$passing_num."\n");
if ($points_num >= $passing_num)
{
fwrite($f, "User passes\n");
}
else
{
fwrite($f, "User fails\n");
}
fwrite($f, "--------------------------\n");
if($f)
{
fclose($f);
}
?>
I'm not sure if this will fix everything but
$sql->execute(array(":version" => $version, ":points" => $points, ":passing_percent" => $passing_percent, ":gained_score" => $gained_score, ":username" => $username, ":email" => $email, ":quiz_title" => $quiz_title));
should be:
$sql->execute(array("version" => $version, "points" => $points, "passing_percent" => $passing_percent, "gained_score" => $gained_score, "username" => $username, "email" => $email, "quiz_title" => $quiz_title));
(remove the : from the array. it is only for PDO to 'name' the variables).
Related
How can I verify successful row creation (and modification) when using prepared_insert in PDO?
Here is my code:
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
$data = array_filter($data);
//var_dump ($data);
prepared_insert($conn, 'products', $data);
$id = $conn->lastInsertId();
if ($id > 0) {
echo json_encode(array('response'=>'success','message'≥'Row successfully added'));
}else{
echo json_encode(array('response'=>'danger','message'≥'Row not successfully added'));
}
}catch(PDOException $e){
echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
$conn = null;
As you can see, right now I am doing it by using lastInsertId() but I do not think that's the correct way to do it.
Additionally, if the row was not created, how can I capture the error behind it and report it?
you not need create this condition :
if ($id > 0) {
echo json_encode(array('response'=>'success','message'≥'Row successfully added'));
}else{
echo json_encode(array('response'=>'danger','message'≥'Row not successfully added'));
}
because you using try and catch.. you can make sure it with database transaction.. try to commit and catch to rollback..
So I am creating a login system that uses php classes to insert data into database. The following is the insert method for the database.
public function insert($table, $fields = array()){
if(count($fields)){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= '?';
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (".implode(', ', $keys).") VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
}
return false;
}
The next method is where i grab input fields to input into database.
public function create($fields = array()) {
if ($this->_db->insert('users', $fields)) {
throw new Exception('There was a problem with creating an account. Try again later.');
}
}
And this is how I am registering the user.
if ($validation->passed()) {
//register user
$user = new User();
try {
$salt = Hash::salt(32);
$address =
Input::get('street_address') . ':' .
Input::get('city') . ':' .
Input::get('state_province') . ':' .
Input::get('zip_code')
;
echo $address;
$user->create(array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'address' => $address,
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'date_joined' => date('Y-m-d H:i:s'),
'groups' => 1
));
Session::flash('home', 'You have been registered and can now log in!');
header('Location: index.php');
} catch(Exception $e) {
die($e->getMessage());
}
// Session::flash('success', 'You registered successfully!');
// header('Location: index.php');
} else {
//show errors
foreach($validation->errors() as $error) {
echo $error . "<br>";
}
}
I tried fixing the query and making sure there was no mistakes, but I can't seem to find anything wrong with it.
I have a table like so.
CREATE TABLE `GBPAUD` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`currency_pair` varchar(11) NOT NULL DEFAULT '',
`date` datetime NOT NULL,
`sell` float NOT NULL,
`buy` float NOT NULL,
`spread` float NOT NULL,
PRIMARY KEY (`id`)
)
I have written a script that opens CSV files, itterates the rows and inserts them into the table.
After the script has run and i look in the database the table appears like this.
The code that inserts the data looks like so.
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
I print out the values just before the exacute stament and the values are correct.
Array
(
[:currency_pair] => GBP/AUD
[:date] => 2007-11-01 14:06:04.000
[:buy] => 2.273400
[:sell] => 2.272500
[spread] => 0
)
Anyone have any idea why its not inserting my data?
EDIT:
DB connection code
define("DSN", "mysql:dbname=rates_test;host=localhost;port=3306");
define("USER", "blah");
define("PASS", "blah");
$pdo = new PDO(DSN, USER, PASS);
EDIT 2
I have taken the insert out of the function and added to the while loop im doing so you can see whats happening.
while( false !== ( $data = fgetcsv($file) ) ) {
if(array(null) !== $data){ //skip blank lines
$currencyPair = $data[$column['columns']['instrument']];
$date = $data[$column['columns']['date']];
$sell = $data[$column['columns']['sell']];
$buy = $data[$column['columns']['buy']];
$spread = (float)$buy - (float)$sell;
echo "value => " . $currencyPair . "\r\n";
echo "value => " . $date . "\r\n";
echo "value => " . $sell . "\r\n";
echo "value => " . $buy . "\r\n";
echo "value => " . $spread . "\r\n";
echo var_dump(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, ':spread' => (float)$spread));
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, ':spread' => (float)$spread));
}
}
and here is the result
value => GBP/AUD
value => 2007-10-28 21:21:48.000
value => 2.229000
value => 2.229900
value => 0
array(5) {
[":currency_pair"]=> string(15) "GBP/AUD"
[":date"]=> string(47) "2007-10-28 21:21:48.000"
[":buy"]=> float(0)
[":sell"]=> float(0)
[":spread"]=> float(0)
}
Edit 3:
I solved it, but its a bit hacky. Also i have no control over over these CSV's so any invisible characters can be in it. Can anyone please confirm if this is enough to handle any invisible characters there may be? ( i have not put this into a function yet, but i am doing the same for ever variable im inserting)
$buy = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $buy);
$buy = (strpos($buy, ':') && strpos($buy, '-')) ? array_shift(explode('.', $buy)) : $buy;
I do not like what i am doing with the date, but i cannot think of any other ways (i cannot parse a legitamate date straight from the CSV because of the invisable characters) even without the invisible characters removed i cannot parse a date because some feilds have more than 6 micro seconds (PHP can only handel 6)
I just wrapped a bit of code around your posted code and it works fine. I did not even change the code for the spread to :spread suggestion.
I did however add a try/catch block as I see you set the mode to throw Exceptions, but the catch block was never activated.
<?php
class tst
{
private $pdo;
private $instrument = 'gbp_aud';
public function __construct()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'test';
/*** mysql password ***/
$password = 'test';
/*** database name ***/
$dbname = 'test';
try {
$this->pdo = new PDO("mysql:host=$hostname;dbname=$dbname;charset=UTF8", $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,'SET NAMES UTF8');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
catch(PDOException $e) {
print_r($this->pdo->errorInfo());
exit;
}
}
public function doit($currencyPair, $date, $buy, $sell, $spread){
$this->insert($currencyPair, $date, $buy, $sell, $spread);
}
}
$test = new tst();
$currencyPair = 'GBP/AUD';
$date = '2007-11-01 14:06:04.000';
$buy = 2.273400;
$sell = 2.272500;
$spread = 0;
$test->doit($currencyPair, $date, $buy, $sell, $spread);
$currencyPair = 'GBP/AUD';
$date = '2007-11-02 13:06:04.000';
$buy = 2.276600;
$sell = 2.278800;
$spread = 0.4;
$test->doit($currencyPair, $date, $buy, $sell, $spread);
Results:
I just read your last question, and I have to assume that you still have some odd characters in your data feed to this process.
Do a var_dump() of the array that you feed to the ->execute() statement, that will likely show more than a simple print_r()
UPDATE
The issue is that the older files are encoded in UNICODE and the new files are simple ASCII single byte encoded.
I converted the Older files offline so to speak back to ASCII and this code loaded an old and new file quite happily
The only remaining complication if that the older files dont have column names on row 1 and the field order is a little different, but thats just a FLOC. See the code below.
<?php
class tst
{
private $pdo;
private $instrument = 'gbp_aud';
public function __construct()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'test';
/*** mysql password ***/
$password = 'test';
/*** database name ***/
$dbname = 'test';
try {
$this->pdo = new PDO("mysql:host=$hostname;dbname=$dbname;charset=UTF8", $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,'SET NAMES UTF8');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
catch(PDOException $e) {
print_r($this->pdo->errorInfo());
exit;
}
}
public function doit($currencyPair, $date, $buy, $sell, $spread){
$this->insert($currencyPair, $date, $buy, $sell, $spread);
}
}
$test = new tst();
// One old and one new format file
$files = array('GBP_AUD_Week1.csv', 'GBP_AUD_Week5.csv');
foreach ($files as $file) {
$old_format = true;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// test old or new file layout
if ( $data[0] == 'lTid' ) {
// New file layout
$old_format = false;
// Skip the title row
continue;
}
if ( $old_format ) {
$test->doit($data[1], $data[2], $data[3], $data[4], $data[4]-$data[3]);
} else {
$test->doit($data[2], $data[3], $data[4], $data[5], $data[5]-$data[4]);
}
}
fclose($handle);
}
}
I have a class formhandller like this
<?php
include "config.php";
class formhandller {
var $dbinstance;
var $lastinsertedid;//The id from the basic information tabel
function __construct(){
$this->connectDb();
}
function pdoMultiInsert($tableName, $data, $pdoObject){
//Will contain SQL snippets.
$rowsSQL = array();
//Will contain the values that we need to bind.
$toBind = array();
//Get a list of column names to use in the SQL statement.
$columnNames = array_keys($data[0]);
//Loop through our $data array.
foreach($data as $arrayIndex => $row){
$params = array();
foreach($row as $columnName => $columnValue){
$param = ":" . $columnName . $arrayIndex;
$params[] = $param;
$toBind[$param] = $columnValue;
}
$rowsSQL[] = "(" . implode(", ", $params) . ")";
}
//Construct our SQL statement
$sql = "INSERT INTO `$tableName` (" . implode(", ", $columnNames) . ") VALUES " . implode(", ", $rowsSQL);
//Prepare our PDO statement.
$pdoStatement = $pdoObject->prepare($sql);
//Bind our values.
foreach($toBind as $param => $val){
$pdoStatement->bindValue($param, $val);
}
//Execute our statement (i.e. insert the data).
try {
return $pdoStatement->execute();
} catch(PDOException $e) {
var_dump($e->getMessage());
//show error
error_log($query." :".$e->getMessage(). "\n", 3, getcwd() . "/var/tmp/sql_error.log");
exit;
}
}
private function connectDb(){
try {
//create PDO connection
$this->dbinstance = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$this->dbinstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
error_log($query." :".$e->getMessage(). "\n", 3, getcwd() . "/var/tmp/sql_error.log");
exit;
}
}
public function postBasicinformation(){
//Add the variables coming from the form .
$stmt = $this->dbinstance->prepare('INSERT INTO basic_information (company,name,designation,email,direct_line,mobile) VALUES (:company, :name, :designation, :email, :directline, :mobile)');
$stmt->execute(array(
':company' => $_POST['company'],
':name' => $_POST['name'],
':designation' => $_POST['designation'],
':email' => $_POST['email'],
':directline' => $_POST['directline'],
':mobile' => $_POST['mobile'],
));
$this->lastinsertedid = $this->dbinstance->lastInsertId('id');
//echo $this->lastinsertedid;
//$this->dbinstance=null;
}
public function postProjectawards(){
//An example of adding to our "rows" array on the fly.
for($i=0;$i<sizeof($_POST['nominee_company']);$i++){
$rowsToInsert[] = array(
'biid' => $this->lastinsertedid,
'award_type' => 'pa',
'category' => $_POST['nominee_category'][$i],
'company' => $_POST['nominee_company'][$i],
'name' => $_POST['nominee_name'][$i],
'designation' => $_POST['nominee_designation'][$i],
'award_title' => $_POST['nominee_title'][$i],
'contact' => $_POST['nominee_contact'][$i],
'email' => $_POST['nominee_email'][$i],
'remark' => $_POST['remarks'][$i]
);
}
//var_dump($rowsToInsert);
//Call our custom function.
$y =$this->pdoMultiInsert('nominee', $rowsToInsert, $this->dbinstance);
//$this->dbinstance=null;
}
}
Now my redirect page is like this
<?php
include "controller/formhandller.php";
$x = new formhandller();
if(isset($_POST['steps'])){
if($_POST['steps']==1){
$x->postBasicinformation();
$url = "nominee.php";
header('Location: '.$url);
die();
}
if($_POST['steps']==2){
$x->postProjectawards();
$url = "nominee2.php";
header('Location: '.$url);
die();
}
}
else {
header('Location: '.'index.php');
die();
}
When I am saving the first step that is using postBasicinformation() this function .
It saves in a table called basic_information and gets the id of the inserted row and initialize it to the variable
$lastinsertedid
I want to use this variable in all the next steps to store in other tables.
But right now I am getting NULL
any Idea
Thanks.
I think you are getting confused about the life cycle of a php script.
Anything you do in xxx.php is lost once that script finishes. All objects instantiated during the execution of xxx.php with be lost forever once it finishes.
If you want to preserve some information created in xxx.php for use in yyy.php you have to save it somewhere, either a file or a database or the SESSION or possibly a caching system.
I think this is where you are getting confused. So as you said in a comment if you want to use this lastinsertid in another script the most obvious place to save it between scripts is the $_SESSION array
Please find below a script that scrapes an HTML table that should return data in my Database ( SQL|PhpMyAdmin ). I run the script in my browser using ( XAMPP)
The scraper works fine, it can display data in the browser or download as an excel file. I added a connection String to SQL using [ $conn = mysql_connect ], However, I read this method its been deprecated and its better to use [mysqli_connect ] or PDO.
Questions :
If I use mysqli_connect, I dont encounter problems connecting to my database but the returned data is missing some rows. For example the table has 100 rows and I would just find 80 rows in the database. What could be causing that ? I dont think from the script otherwise I wouldn't see the complete results in the browser
I tried the PDO ( see code below ) , the connection is successfull however no data is entered in my database. Is there any syntax Error ?
I don't mind using mysql_connect , mysqli_connect or PDO as long as I have all rows in my database without anything missing.
Please advise what connection String to use and why there are missing rows . The script is working well and returned data in browser is the same as the URL scraped.
Code 1 : Using mysqli_connect Method + Script overview
$connection = mysqli_connect("localhost", "username", "password", "test");
if (!$connection) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Host information: %s\n", mysqli_get_host_info($connection));
$OutPut_Excel = $_GET['xls'];// 0 web page or 1 output excel
$show_Country = $_GET['show'];// 0 or 1
$urls = "
http://www.URL.com
";
//output excel
if($OutPut_Excel == "1")
{
header("Content-Type: application/vnd.ms-execl;charset=iso-8859-1");
header("Content-Disposition: attachment; filename=data.xls");
header("Pragma: no-cache");
header("Expires: 0");
}
set_time_limit(0);
ini_set('memory_limit', '-1');
ini_set('display_errors',true);
//output html
if($OutPut_Excel == "0")
{
?>
<html>
<head>
<title>scraper</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
}
if($OutPut_Excel == "0")
{
if($show_Country)
{
$nameCountry = '<td>Country</td>';
}
echo "<table border='1'><tr><td>Name</td><td>Surname</td>
<td>Email</td><td>Address</td><td>City</td><td>Profession</td> <td>Phone</td>$Country</tr>";
}
else
{
echo "Name"."\t";
echo "Surname"."\t";
echo "Email"."\t";
echo "Address"."\t";
echo "City"."\t";
echo "Profession"."\t";
echo "Phone"."\t";
if($show_Country)
{
echo "Country"."\t";
}
echo "\t\n";
}
include 'dom.php';
$arrurl = explode(';',$urls);
foreach ($arrurl as $u)
{
$url = trim($u);
$html = file_get_html($url);
$string = $html->find("table[width=720]",0)->find("font[size=5]",0)->plaintext;
$arr = explode(' at ',$string);
$Satellite = trim($arr[0]);
$Degree = trim($arr[1]);
$k = 0;
foreach ($html->find("table[width=720]") as $d)
{
$text = $d->outertext;
$arr = explode('<td',$text);
$out = "";
foreach ($arr as $t)
{
$arr1 = explode('<font',$t);
$count_font = count($arr1);
$arr2 = explode('</font>',$t);
$count_end_font = count($arr2);
$need_count = $count_font-$count_end_font;
$str = "";
for($j=1;$j<=$need_count;$j++)
{
$str=$str."</font>";
}
if($out == "")
{
$out .= str_replace('</td>',$str,$t);
}
else
{
$out .= "<td".str_replace('</td>',$str,$t);
}
}
ECT... Some more code
echo "$Name"."\t";
echo "$Surname"."\t";
echo "$Email"."\t";
echo "$Address"."\t";
echo "$City"."\t";
echo "$Profession"."\t";
echo "$Phone"."\t";
if($show_Country)
{
echo "$Country"."\t";
// SQL QUERY - WORKS FINE BUT SOME ROWS MISSING
}
$connection->query("INSERT INTO Directory (Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES('$Name','$Surname','$Email','$Address','$City','$Profession','$Phone','$Country')");
CODE 2 - PDO Connection - Returned Data is not entered in database
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
try{
$stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES($Name, $Surname, $Email, $Address, $City, $Profession, $Phone, $Country)');
$stmt->execute(array('Name' => $Name, 'Surname' => $Surname, 'Email' => $Email, 'Address' => $Address, 'City' => $City, 'Profession' => $Profession, 'Phone' => $Phone, 'Country' => $Country));
$affected_rows = $stmt->rowCount();
} catch(PDOException $ex) {
echo "An Error occured!";
some_logging_function($ex->getMessage());
}
Try
$stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES($Name, $Surname, $Email, $Address, $City, $Profession, $Phone, $Country)');
$stmt->execute(array('Name' => $Name, 'Surname' => $Surname, 'Email' => $Email, 'Address' => $Address, 'City' => $City, 'Profession' => $Profession, 'Phone' => $Phone, 'Country' => $Country));
to
$stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES(:Name, :Surname, :Email, :Address, :City, :Profession, :Phone, :Country)');
$stmt->execute(array(':Name' => $Name, ':Surname' => $Surname, ':Email' => $Email, ':Address' => $Address, ':City' => $City, ':Profession' => $Profession, ':Phone' => $Phone, ':Country' => $Country));
http://www.php.net/manual/fr/pdo.prepare.php
On your mysql_query() function call you need to provide the database connection $conn.
It should be like this:
$sql = mysql_query("your sql query", $conn);
Re not all rows being inserted, it must be an error during the insert. Try modifying you code like this so MySQL errors are printed:
$connection->query("your sql query") or die(mysqli_error($connection));
Most likely it is an apostrophe ( ' ) somewhere in one of the values you are inserting. You may need to remove or escape them.