note 127632 added to mysqli.quickstart.prepared-statements

From: Date: Thu, 15 Sep 2022 15:10:35 +0000
Subject: note 127632 added to mysqli.quickstart.prepared-statements
Groups: php.notes 
Request: Send a blank email to php-notes+get-219576@lists.php.net to get a copy of this message
<?php require_once "Database.php"; // Database connection class Article { private $id; private $name; private $description; private $price; /** * @param $id * @param $name * @param $description * @param $price */ public function __construct($name, $description, $price, $id=0) { $this->id = $id; $this->name = $name; $this->description = $description; $this->price = $price; } /** * @inheritDoc * The create() function is able to carry out an INSERT query using Prepared Statements */ public function create() { // Working with Getters $name = $this->getName(); $description = $this->getDescription(); $price = $this->getPrice(); $mysqli = Database::connect(); // Database connection with mysqli $sql = "INSERT INTO articles (name, description, price) VALUES (?,?,?)"; // SQL query if ($stmt = $mysqli->prepare($sql)) { // Prepare the SQL query $stmt->bind_param("ssd", $name, $description, $price); // Bind the three parameters $stmt->execute(); // Execute the prepared statement if ($stmt->affected_rows == 1) { // If the statement executed successfully do this ... header("Location: index.php"); } else { // If the statement was not executed successfully do sth else ... echo "Database error"; } $this->id = $mysqli->insert_id; // Update the id $stmt->close(); // Close the statement } } } // Calling function from anywhere else $article = new Article($name, $description, $price); // Create new Article object $article->create(); // Call the function ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.173 (proxied: 185.7.124.65) ---- Manual Page -- https://php.net/manual/en/mysqli.quickstart.prepared-statements.php Edit -- https://main.php.net/note/edit/127632 Del: integrated -- https://main.php.net/note/delete/127632/integrated Del: useless -- https://main.php.net/note/delete/127632/useless Del: bad code -- https://main.php.net/note/delete/127632/bad+code Del: spam -- https://main.php.net/note/delete/127632/spam Del: non-english -- https://main.php.net/note/delete/127632/non-english Del: in docs -- https://main.php.net/note/delete/127632/in+docs Del: other reasons-- https://main.php.net/note/delete/127632 Reject -- https://main.php.net/note/reject/127632 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219576) next »