keep printing over and over connected to database - php

Update: my code works if I put my database file in script file, so not sure why is it not working if I have different file
I have a csv file that I parse at input as in command line and use that file (csv) to insert those values of csv (name, surname and email) to mysql. When I run my code it keep printing over and over until it runs out of memory connected to database what am I doing wrong? ANy help is appreciated.
script.php
<?php
require "database.php";
$options = ['file:'];
$values = getopt(null, $options);
$lines = file($values['file'], FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$csv = array_map('str_getcsv', $lines);
$col_names = array_shift($csv);
$users = [];
foreach($csv as $row) {
$users[] = [
$col_names[0] => ucfirst(strtolower($row[0])),
$col_names[1] => ucfirst(strtolower($row[1])),
$col_names[2] => filter_var(strtolower($row[2]), FILTER_VALIDATE_EMAIL),
];
$stmt = $dbh->prepare("INSERT INTO users(name, surname, email)
VALUES(:name, :surname, :email)");
$stmt->bindParam(':name', $col_names[0]);
$stmt->bindParam(':surname', $col_names[1]);
$stmt->bindParam(':email', $col_names[2]);
$stmt->execute();
}
$dbh = null;
?>
database.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'yourpasswordhere';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=userDetails", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>

Related

Insert multiple rows using form and PDO

Hello guys i am stuck in PHP code to Insert multiple rows using form and PDO
Below my code please help me to fix it
I'll appreciate all comments and suggested solutions
and forgive my mistakes because I am new i PHP
HTML code
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<hr>
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP Code
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = input_checker($_POST["firstname"]);
$lastname = input_checker($_POST["lastname"]);
$email = input_checker($_POST["email"]);
foreach ($row as $rows) {
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO memo (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $rows);
$stmt->bindParam(':lastname', $rows);
$stmt->bindParam(':email', $rows);
$stmt->execute();
echo "New records created successfully";
}
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
function input_checker($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Indent please, it's hard to read.
It can't work.
DONT FOREACH THE QUERY. You'll send one query with bad datas as many times as you have elements in $rows array
What you're doing here is sending nothing cause $rows don't exist.
So here are the steps.
Do
$rows = array($firstname, $lastname, $email);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname, email)
VALUES (NULL, :firstname, :lastname, :email)");
foreach($rows as $key => $value){
$stmt->bindParam($key, $value);
}
$stmt -> execute();
OR you can try building the query this way :
DB_connect :
<?php
$db_username = "root";
$db_password = "";
$db_host = "localhost";
$db_name = "veterinaires";
/* PDO EN FR OU EN ARABE C ISSI */
$db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
Query :
$query = "INSERT INTO patients
(ID,
pet_name,
breed,
colour,
sex,
date_of_birth,
microchip_tatoo,
comment,
owner_ID)
VALUES
(NULL,
:pet_name,
:breed,
:colour,
:sex,
:date_of_birth,
:microchip_tatoo,
:comment,
:owner_ID)";
$query_params = array(':pet_name' => $pet_name,
':breed' => $breed,
':colour' => $colour,
':sex' => $sex,
':date_of_birth' => $date_of_birth,
':microchip_tatoo' => $microchip_tatoo,
':comment' => $comment,
':owner_ID' => $_SESSION['ID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$check = true;
}catch(PDOException $ex){
$check = false;
die("Failed to run query: " . $ex->getMessage());
}
?>

PHP fails at inserting values into database

I'm using a WordPress theme for my site, but customizing it has given me such a headache that we are trying to use our own hand written from instead of the one provided by WordPress.
I have written a php-script that should insert values from this form into a custom table in a custom database outside of the wordpress database. How ever when I try to run it I get no error messages, and no data is inserted into the database.
my PHP code, please not that I have changed the $user and $pass to not show here. I've tested the login info used in this script via terminal on my database, and it worked fine. See the full file here page.sign.php
if(isset($_POST['submit'])) {
$lastname = $_POST["lname"];
$firstname = $_POST["fname"];
$email = $_POST["email"];
$affiliation = $_POST["affiliation"];
$country = $_POST["X"];
$position = $_POST["position"];
$hindex = $_POST["scholar"];
$gender = $_POST["optionsRadios"];
$city = $_POST["city"];
$webpage = $_POST["webpage"];
$newsletter = $_POST["newsletter"];
//Source https://gist.github.com/adrian-enspired/385c6830ba2932bc36a2
$host = "localhost";
$dbname = "petition";
$user = "<username>";
$pass = "<password>";
$charset = "UTF8MB4"; // if your db does not use CHARSET=UTF8MB4, you should probably be fixing that
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo "<h1>Error connecting to the database </h1>";
}
$stmt = $pdo->prepare("INSERT INTO petitioners (lastname, firstname, email, affiliation, country, position, hindex, gender, city, webpage, newsletter)
VALUES
(:lastname, :firstname, :email, :affiliation, :country, :position, :hindex, :gender, :city, :webpage, :newsletter)");
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':firstname', $firsname);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':affliation',$affiliation);
$stmt->bindParam(':country',$country);
$stmt->bindParam(':position',$position);
$stmt->bindParam(':hindex',$hindex);
$stmt->bindParam(':gender',$gender);
$stmt->bindParam(':city',$city);
$stmt->bindParam(':webpage',$webpage);
$stmt->bindParam(':newsletter',$newsletter);
$stmt->execute();
echo "<h1>Signatory succefully registered</h1>";
$stmt->close();
$conn->close();
}

PHP pdo insert query not working

<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.

Can't insert data via PDO using associative array

That's how I'm trying to do it:
database.php:
<?php
$host = "host";
$user = "user";
$pass = "password";
$dbname = "database";
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data:
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
try {
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
$STH->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
According to this http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059 it should accept associative array. But instead it does nothing and says that I have an error in this line:
$STH = $DBH->("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
What can be causing it, and how I can actually use an associative array to insert data into MySQL database using PDO?
Hmmmm... There are some flaws I can see:
database.php
$host = "us-cdbrbababababableardb.net";
$user = "b9bababababefc";
$pass = "9c4ababab";
$dbname = "heroku_aabababab49";
$DBH = null;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
try {
// NOTICE: prepare() used and VALUES instead of VALUE
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) values (:name, :message, :date)");
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
// NOTICE: $data has allready been supplied by bindParam()
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
These are just the first few things I could find wrong with the code... Try reading up on the PDO tutorials and functions for better info on what they would need as input.

Data insert into mysql db table using PDO - Doesn't Insert Data

I'm 'Connected to database'. There is no data in the table, and $result doesn't echo anything. Even though I'm 'Connected to database', the error is as follows:
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
I've read the relevant postings, with no luck.
<?php
include("/directory outside of html/db.php");
try {
$dbh = new PDO("mysql:host=$host;database=$database", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//try to insert data
$fname = 'BOB';
$lname = 'JONES';
$email = 'me#mymail.com';
$phone = '410-310-3456';
$resident = TRUE;
$age = '25=30';
$zip = '23456';
$result = FALSE;
$stmt = $dbh->prepare('INSERT INTO volunteers
(
lname,
fname,
email,
)
VALUES
(
:lname,
:fname,
:email,
)');
$result = $stmt->execute(array(
':lname' => $lname,
':fname' => $fname,
':email' => $email,
));
echo $result;
//catch any errors from try()
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Use dbname= instead of database= , like this:
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
Alternatively, you can select later a different database with USE, like this:
$dbh->query("use newdatabase");

Categories