How do I pass a database connection into a method PHP - php

I have a class in PHP and one of the methods needs to access a database.How do I correctly pass a database connection variable to a method? Does it get passed as a parameter through the constructor or method? Or is it something completely different?

Check the following updated answer. Tested and working.
<?php
class SomeClass
{
function setDb($servername, $username, $password, $database)
{
// Create the database connection and use this connection in your methods as $this->conn
$this->conn = new mysqli($servername, $username, $password, $database);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
echo "New successful connection to myDb \n";
}
public function createTable()
{
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($this->conn->query($sql) === TRUE) {
echo "New table created successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $this->conn->error;
}
}
public function normalInsertDb()
{
// sql to insert record using normal query
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($this->conn->query($sql) === TRUE) {
echo "New record inserted successfully using normal sql statement \n";
} else {
echo "Error: " . $sql . "<br>" . $this->conn->error;
}
}
public function preparedInsertDb()
{
// prepare and bind
$stmt = $this->conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records inserted successfully using PREPARED STATEMENTS \n";
$stmt->close();
$this->conn->close();
}
}
$obj = new SomeClass();
$obj->setDb('localhost', 'homestead', 'secret', 'myDb'); //we assume the database myDb exists
$obj->createTable();
$obj->normalInsertDb();
$obj->preparedInsertDb();
My Result:

If the database connection is used only by one method of your object, there is nothing wrong about passing it as an argument to this method.
However, mostly this is not the case. So you would be better off, when you establish the db connection at an earlier stage (on top of your script) and then pass it as a constructor argument to all objects that will need it. Then, various objects can use the same connection for various methods and internal, private methods, too.
If you want to optimize further, wrap the connection into a dedicated class and use dependency injection to get it into the consumer objects.

Related

How do I insert foreign key value into a table?

I have to insert the values of a donation form into a table. The table has a foreign key 'uid' which is the donor's id. When I tried to insert the data without giving value to foreign key, the insertion failed.
Then I set the FK value to null. In this case the data was inserted into the table but the value of 'uid' (FK) was null obviously. Now how do I insert the correct value? The correct value whould be the uid of the donor who is currently logged in.
<?php
if (!isset($_SERVER['HTTP_REFERER'])) {
header('location:index.php');
exit;
}
include 'header.php';
session_start();
$servername = "localhost";
$username = "root";
$password = "sql";
$db = "sp";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_POST) {
$item = $_POST['item'];
$details = $_POST['details'];
$quantity = $_POST['quantity'];
$sql = "INSERT INTO donation (item, details, quantity) VALUES ('$item', '$details','$quantity');";
if ($conn->query($sql) == true) {
echo "Successful submission";
} else {
echo $sql;
}
$conn->close();
}
The login form should put the user's UID in a session variable. Then you can use that in the INSERT query.
You should also use a prepared statement to prevent SQL injection.
$stmt = $conn->prepare("INSERT INTO donation (uid, item, details, quantity) VALUES (?, ?, ?, ?);");
$stmt->bind_param("iisi", $_SESSION['uid'], $item, $details, $quantity);
if ($stmt->execute()) {
echo "Successful submission";
} else {
echo "Error: $stmt->error";
}

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

Insert stored procedure in PHP

I have a simple insert statement to save form details in PHP.
I want to convert this into store procedure.
Below is my current code how
$servername = "localhost";
$username = "aaaaaa";
$password = "ppppp";
$dbname = "xxxx_database";
$sName = $_POST["name"];
$sEmail = $_POST["email"];
$sPhone = $_POST["Number"];
$sInterest = $_POST["interest"];
$Comments = $_POST["Inquiry"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactForm (Name, Email, PhoneNumber,Interest,Comments) VALUES ('$sName', '$sEmail', '$sPhone','$sInterest', '$Comments')";
if ($conn->query($sql) === TRUE) {
echo "New record created";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
And this is my Store procedure
CREATE DEFINER = `xxx`#`localhost` PROCEDURE `SpInsertContactForm` ( IN `Name` TEXT CHARSET armscii8, IN `Email` TEXT CHARSET armscii8, IN `PhoneNumber` TEXT CHARSET armscii8, IN `Interest` TEXT CHARSET armscii8, IN `Comments` TEXT CHARSET armscii8 ) NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER INSERT INTO ContactForm( Name, Email, PhoneNumber, Interest, Comments )
VALUES (
Name, Email, PhoneNumber, Interest, Comments
)
How can i use this store procedure. I am new to php and mysql need pointer in this.
I use SP as
if (!$mysqli->query("CALL SpInsertContactForm($sName, $sEmail, $sPhone,$sInterest, $Comments)"))
{
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
This doesn't save anything in DB
you cal use this: $mysqli->query("CALL SpInsertContactForm('<your_namevalue>','<your_emailvalue>','<your_phonevalue>','<your_interestvalue>','<your_commentvalue>')
For more please follow the link:
http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

PHP & mySQL obtaining last insert ID

I'm quite new to this php/mysql deal and I'm having a hard time figuring out this situation particularily.
I have two tables, one of them is "dog" table and the other one is the "date" table. In order to insert a record in the "dog" table I MUST first insert a date in the "table" date and get the autoincrement id from that date.
Problem is that I've tried reading several posts on how to get the last insert id from a table you just inserted a record on and I can't seem to make it work.
$sql1="INSERT INTO FECHAS (fecha) VALUES (NOW())";
mysql_query($sql1);
echo $sql1;
$sql3="SELECT LAST_INSERT_ID()";
mysql_query($sql3);
echo $sql3;
$sql2="INSERT INTO PERRO (nombre_perro,FECHAS_id_fecha) VALUES ('$nombre_perro_var', '$last_id')";
echo $sql2;
if (!$mysqli->query($sql2)) {
echo 'Error: ', $mysqli->error;
}
$result2 = mysql_query($sql2);
Please forgive this code, I'm new and learning.
Thanks!
Use mysqli instead of mysql_
Connecting with mysqli:
$connection = mysqli_connect($hostname, $username, $password, $database_name);
Inserting into a table:
mysqli_query($connection, $sql);
Retrieving last inserted id:
$id = mysqli_insert_id($connection);
**Database**
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
**Example (MySQLi Object-oriented)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
***$last_id = $conn->insert_id;***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
**Example (MySQLi Procedural)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
***$last_id = mysqli_insert_id($conn);***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**Example (PDO)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
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);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
***$last_id = $conn->lastInsertId();***
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
A procedural solution (although it might be slightly wrong - I'm terrible at PHP)...
<?php
include('path/to/connection/stateme.nts');
$query = "
INSERT INTO fecha (fecha) VALUES (NOW());
";
mysqli_query($db,$query);
$query = "
INSERT INTO perro (nombre_perro,id_fecha) VALUES (?,?);
";
$nombre_perro = 'rover';
$id_fecha = mysqli_insert_id($db);
$stmt = mysqli_prepare($db,$query);
mysqli_stmt_bind_param($stmt, 'si', $nombre_perro,$id_fecha);
mysqli_stmt_execute($stmt);
?>
You might consider binding both queries into a transaction, so that in the event that the second query fails for some reason, then the first query fails too.

MySQLi insert statement to executing

I am writing a simple code in PHP to test my MySql server by , inserting data to my database server
i am executing the file from the internet
URL of executing : Scores2.php?n=asdad&l=345&s=241
PHP Code:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i execute the file , the browser shows this error :
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
I checked the Control Panel in phpMyAdmin and executed the same statement but without variables , and it worked
Rows Types :
name : text
score : int(11)
level : int (11)
Learn how to prepare the query it's not that difficult.
You will avoid sql injection and missing quotes
Use num_rows to check if the record is inserted
Use $conn->error if the prepare() call return false.
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
change query like this

Categories