I am trying to insert form data into MySQL using PHP but somehow the insert query get fired two times.I have attached my code below...please help if anyone know about solution...
<?php
class Product{
// database connection and table name
private $conn;
private $table_name = "lspl_user_profile";
// object properties
public $id;
public $fname;
public $lname;
public $job;
public $dept;
public $email;
public $password;
public function __construct($db){
$this->conn = $db;
}
public function create(){
try{
// insert query
$query = "INSERT INTO lspl_user_profile
SET fname=:fname, lname=:lname, job=:job, dept=:dept, email=:email, password=:password";
// prepare query for execution
$stmt = $this->conn->prepare($query);
// sanitize
$fname=htmlspecialchars(strip_tags($this->fname));
$lname=htmlspecialchars(strip_tags($this->lname));
$job=htmlspecialchars(strip_tags($this->job));
$dept=htmlspecialchars(strip_tags($this->dept));
$email=htmlspecialchars(strip_tags($this->email));
$password=htmlspecialchars(strip_tags($this->password));
// bind the parameters
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':job', $job);
$stmt->bindParam(':dept', $dept);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
// Execute the query
if(empty($fname) ||empty($lname) || empty($job) ||empty($dept) ||empty($email) || empty($password) )
{
return false;
}
else
{
$stmt->execute();
mysqli_close($conn);
return true;
}
}
// show error if any
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
}
?>
This is create_product.php file...
<?php
if($_POST){
// include core configuration
include_once '../config/core.php';
// include database connection
include_once '../config/database.php';
// product object
include_once '../objects/product.php';
// class instance
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
// set product property values
$product->fname = $_POST['fname'];
$product->lname = $_POST['lname'];
$product->job = $_POST['job'];
$product->dept = $_POST['dept'];
$product->email = $_POST['email'];
$product->password = $_POST['password'];
// create the product
echo $product->create() ? "true" : "false";
}
?>
This method send parameters to create_product.php
$.post("api/create_product.php", {
fname: this.state.fname,
lname: this.state.lname,
job: this.state.job,
dept: this.state.dept,
email: this.state.email,
password: this.state.password
}
);
Thank you, peoples..issue is resolved. Actually, I have made one silly mistake in HTML which causing post method invoke two time.
Especially, thanks to ADyson..
Related
I got an error when I want to consume a Rest API using postaman and docker.
The error is marked in this line of code: Error in php Connection Error: could not find driver
<?php
class Materias {
// DB stuff
private $conn;
private $table = 'materias';
// Materias Properties
public $clave_materia;
public $nombre_materia;
public $semestre;
public $creditos;
// Constructor with DB
public function __construct($db) {
$this->conn = $db;
}
// Get Materias
public function read() {
// Create query
$query = 'SELECT * FROM ' . $this->table;
// Prepare statement
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
}
// Get Single Materia
public function read_single() {
// Create query
$query = 'SELECT * FROM ' . $this->table . 'WHERE clave_materia = ?';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Bind clave_materia
$stmt->bindParam(1, $this->clave_materia);
// Execute query
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Set properties
$this->nombre_materia = $row['nombre_materia'];
$this->semestre = $row['semestre'];
$this->creditos = $row['creditos'];
}
// Create Post
public function create() {
// Create query
$query = 'INSERT INTO ' . $this->table . ' SET clave_materia = :clave_materia, nombre_materia = :nombre_materia, semestre = :semestre, creditos = :creditos';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
$this->nombre_materia = htmlspecialchars(strip_tags($this->nombre_materia));
$this->semestre = htmlspecialchars(strip_tags($this->semestre));
$this->creditos = htmlspecialchars(strip_tags($this->creditos));
// Bind data
$stmt->bindParam(':clave_materia', $this->clave_materia);
$stmt->bindParam(':nombre_materia', $this->nombre_materia);
$stmt->bindParam(':semestre', $this->semestre);
$stmt->bindParam(':creditos', $this->creditos);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Update Post
public function update() {
// Create query
$query = 'UPDATE ' . $this->table . '
SET nombre_materia = :nombre_materia, semestre = :semestre, creditos = :creditos
WHERE clave_materia = :clave_materia';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->nombre_materia = htmlspecialchars(strip_tags($this->nombre_materia));
$this->semestre = htmlspecialchars(strip_tags($this->semestre));
$this->creditos = htmlspecialchars(strip_tags($this->creditos));
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
// Bind data
$stmt->bindValue(':nombre_materia', $this->nombre_materia);
$stmt->bindValue(':semestre', $this->semestre);
$stmt->bindValue(':creditos', $this->creditos);
$stmt->bindValue(':clave_materia', $this->clave_materia);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Delete Post
public function delete() {
// Create query
$query = 'DELETE FROM ' . $this->table . ' WHERE clave_materia = :clave_materia';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
// Bind data
$stmt->bindParam(':clave_materia', $this->clave_materia);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
}
Error:
Connection Error: could not find driver<br />
<b>Fatal error</b>: Uncaught Error: Call to a member function prepare() on null in /var/www/html/models/Materias.php: 24
Stack trace:
#0 /var/www/html/api/materias/read.php(17): Materias->read()
#1 {main
}
thrown in <b>/var/www/html/models/Materias.php</b> on line <b>24</b><br />
**bd connection**
<?php
class Database {
// DB Params
private $host = 'localhost';
private $db_name = 'reticula';
private $username = 'root';
private $password = 'test ';
private $conn;
// DB Connect
public function connect() {
$this->conn = null;
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
return $this->conn;
}
}
This is where you call matters
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Materias.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate blog post object
$materias = new Materias($db);
// Blog post query
$result = $materias->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if($num > 0) {
// Post array
$materias_arr = array();
// $posts_arr['data'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$materias_item = array(
'clave_materia' => $clave_materia,
'nombre_materia' => $nombre_materia,
'semestre' => $semestre,
'creditos' => $creditos
);
// Push to "data"
array_push($materias_arr, $materias_item);
// array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($materias_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
I started to learn PHP, have made a great way for myself (not for PHP world) but I cannot succeed updating the information part.. I have problem about updating multiptle tables, and keep receiving this nice error: Could not update data: Query was empty.
I've searched a lot, have been fighting with that for a week and tried to do my best but no result. That's why I am posting here. By the way I know that my code is not neither whole PDO nor MYSQLI but I'm trying my best to learn and implement them as well..
I have got 3 tables now: Students - LessonsBought - Payments.
1) students_id is a joined one with students_id in other tables.
2) students_id is a foreign Key with lessonsbought_id and payments_id
(InnoDB)
Here is my code :
<?php
$servername = "localhost";
$username = "MY-DB-USERNAME";
$password = "MY-DB-PASSWORD";
$dbname = "MY-DB-NAME";
$conn = mysql_connect($servername, $username, $password, $dbname);
if(isset($_POST['update']))
{
$students_name = $row['students_name'];
$students_phone = $row['students_phone'];
$students_email = $row['students_email'];
$students_grade = $row['students_grade'];
$students_reg_date = $row['students_reg_date'];
$lessonsbought_type = $row['lessonsbought_type'];
$lessonsbought_hour = $row['lessonsbought_hour'];
$payment_total = $row['payment_total'];
$payment_method = $row['payment_method'];
$payment_done = $row['payment_done'];
$payment_waiting = $row['payment_waiting'];
$students_id = $_GET["id"];
$sql = mysql_query("UPDATE students,lessonsbought,payment SET
students_name = '$students_name', students_phone = '$students_phone',
students_email = '$students_email', students_grade = '$students_grade',
students_reg_date = '$students_reg_date',
lessonsbought_type= '$lessonsbought_type',
lessonsbought_hour='$lessonsbought_hour',payment_total='$payment_total',
payment_method = '$payment_method', payment_done='$payment_done',
payment_waiting = '$payment_waiting', WHERE students_id =
'$students_id'");
$retval = mysql_query( $sql, $conn );
if(!$retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n <font color='green'>
<b>Record deleted successfully</b><font><br />
<a class='buttons' href='/result.php'>Turn Back To Result Page</a>";
}
?>
first you have to select database
mysql_select_db("database_name");
secondly use separate update query to update different table
thirdly you are calling mysql_query inside another mysql_query.
your sql variable will be just query. like shown below
$sql="UPDATE students SET students_name = '$students_name', students_phone = '$students_phone' WHERE students_id = '$students_id'";
lastly Please stop using mysql_* functions.
I have taken some of your code and added it into PDO so you can see how you should be doing this. In this instance it'll work also once all fields have been entered;
Firstly, set yourself up a database connection file:
class Database
{
private $host = "localhost";
private $db_name = "dbname";
private $username = "user";
private $password = "pass";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Then, I'd make a DBCommon file also. You need to ensure you require_once the database connect file:
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Then you need to make your classes, so for this one it'd be for example, class student;
class student extends DBCommon
{
public function __construct()
{
parent::__construct();
}
public function updateStudent($name, $phone, $email, $grade)
{
$userid = $_SESSION['user_session'];
$stmt = $this->runQuery("UPDATE `tablename` SET `students_name` = :sname, `students_phone` = :phone, `students_email` = :email, `students_grade` = :grade WHERE `students_id` = :sid");
$stmt->bindParam(array(':sname' => $name, ':phone' => $phone, ':email' => $email, ':grade' => $grade, ':sid' => $userid));
$stmt->execute();
echo "Your Records have now been updated.";
}
}
You can add a try / catch block around these to pass back an error message.
Then within your form file you'd need to include the classes file and then create the class and then form your trigger for the code to run when you press the submit button like below:
require_once ('class.file.php');
$class = new student();
if (isset($_POST['update']))
{
$class->updateStudent($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['grade']);
}
I know this doesn't precisely tell you what you've done wrong but the major wrong thing you have done is gone via MySQL_. This way is a much cleaner and effective way.
P.S. Always bind your params never use '{$var}' within your queries as you'll be subject to vulnerabilities.
Alright so my problem is simple, Im trying to get results from a query but it always returns that there are no users registered with the username.
<?php
require "assembly/oop/sql_classbuild.php";
class player {
private $name;
private $age;
private $gender;
private $location;
public function createNew($name, $age, $gender, $location) {
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("INSERT INTO players (name, age, gender, location) VALUES (?,?,?,?)");
$stmt->bind_param("siss", $name, $age, $gender, $location);
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->location = $location;
$stmt->execute();
$stmt->close();
$conn->close();
}
public function isRegistered($name) { //problematic code
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("SELECT name FROM players WHERE name=?");
$stmt->bind_param("s", $name);
$stmt->execute();
if($stmt->num_rows >= 1) { //if there is a registered member
$stmt->close();
$conn->close();
return true;
}
else {
$stmt->close();
$conn->close();
return false;
}
}
}
?>
Now I also tried to print num_rows but it just returns 0 as if there are no results inside the DB.
The usage is quite simple
if($player->isRegistered("Test") == true) {
echo "Hello";
}
else {
echo "Non-existing user";
}
SQL screenshot
http://imgur.com/a/TXqiJ
Also this is the sql class pastebin.com/Evg13CUc
The problem was resolved.
I used $stmt->store_result(); which somehow worked out and it gave me the good results.
How can I run the functions save and update? It seems there's no error on my code..but still is not functioning. I need to save and update with the shortest code..thanks!
<?php
$mysqli = new mysqli("localhost","root","","sample_db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$title = $_POST['title'];
$author = $_POST['author'];
$content = $_POST['content'];
$action = $_POST['action_type'];
$blog_id = $_GET['blog_id'];
function save()
{
$insert_query = "INSERT INTO tb_blogs (`title`, `author` , `content`) values ('{$title}','{$author}','{$content}')";
$mysqli->query($insert_query);
}
function update()
{
$update_query = "UPDATE tb_blogs SET `title` = '{$title}', `author` = '{$author}', `content` = '{$content}' WHERE id = '{$blog_id}'";
$mysqli->query($update_query);
}
if(isset($_POST["submit"])) {
if($action=='create') {
save();
}
elseif($action=='update') {
update();
}
}
I know this has been marked as answered, but I think it's important to show a bind parameter example. This is a bit more complex of a solution, mind you, but it's fairly organized so it should be fairly easy to dissect. Also this is just an example, there are many ways to do this script with bind parameters. The bind parameters in the functions is the most important part really:
/classes/class.DatabaseConfig.php
<?php
// Database configuration meant for connection
class DatabaseConfig
{
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
public function connectMySQLi($host = "localhost", $username = "username", $password = "password", $database = "database")
{
// Create connection
try {
$mysqli = new mysqli($host, $username, $password, $database);
return $mysqli;
} catch (mysqli_sql_exception $e) {
// Print real error if admin, or write to
// secured log file
// throw $e;
die("Connection has failed.");
}
}
}
/classes/class.Db.php
<?php
// Singleton-based class to re-use instantiated resources
class Db
{
private static $singleton;
// Default connection
public static function mysqli()
{
if(empty(self::$singleton)) {
$con = new DatabaseConfig();
self::$singleton = $con->connectMySQLi();
}
return self::$singleton;
}
}
/functions/function.save.php
<?php
// I have chosen a singleton, but you can pass your db connection as a
// second argument like save($array,$mysqli)
function save($settings = false)
{
// Because the the class allows for a static variable, you can
// connect straight in the class without using globals
$mysqli = Db::mysqli();
// Use bind_param/prepare/execute for safe queries
$stmt = $mysqli->prepare("INSERT INTO `tb_blogs` (`title`, `author` , `content`) values (?,?,?)");
// You can do checks on these variables to see that they are filled out, I have not though
$stmt->bind_param("sss",$settings['title'],$settings['author'],$settings['content']);
$stmt->execute();
}
/functions/function.update.php
<?php
function update($settings = false)
{
$mysqli = Db::mysqli();
$stmt = $mysqli->prepare("UPDATE `tb_blogs` SET `title` = ?, `author` = ?, `content` = ? WHERE id = ?");
$stmt->bind_param("sssi",$settings['title'],$settings['author'],$settings['content'],$settings['blog_id']);
$stmt->execute();
}
index.php
<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// You can make a similar autoloader-type function as well instead of
/// manually writing a crap-load of includes
include_once("functions/function.save.php");
include_once("functions/function.update.php");
// Do single wrapper for submit
if(isset($_POST['submit'])) {
// Check for create
if($_POST["action_type"] =='create')
save($_POST);
// Check for update
elseif($_POST["action_type"] =='update')
update($_POST);
}
I am connecting xcode to webservices using, ASIHTTPRequest, and the mysqli prepare statement and also JSON.
Whatever i do i get only one single Mysql-record in xcode as a result.
I have looked everywhere and i have used Ray Wenderlich's "Promo code" example.
I guess i have to learn a bit here, but i just cannot find the answer.
Who can point me into the right direction?
Thank you in advance,
See the code below
// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
class GetLevelAPI {
private $db;
// Constructor - open DB connection
function __construct() {
$this->db = new mysqli('localhost', 'root', '', 'madmagnets');
$this->db->autocommit(FALSE);
}
// Destructor - close DB connection
function __destruct() {
$this->db->close();
}
// Main method to post user info
function getLevel() {
// Check for required parameters
if (isset($_POST["username"])) {
// Put parameters into local variables
$usernameQ = $_POST["username"];
// fire the query
$stmt = $this->db->prepare('SELECT level_id, username, filename from
mm_levels WHERE username=? ');
$stmt->bind_param("s", $usernameQ ) ;
$stmt->execute();
$stmt->bind_result($id1, $username, $filename );
while ($stmt->fetch()) {
break;
}
$stmt->close();
$result = array(
"filename" => $filename ,
"username" => $username ,
);
sendResponse(200, json_encode($result));
return true;
}
sendResponse(400, 'Invalid request');
return false;
} //getLevel
} //GetLevelAPI
$api = new GetLevelAPI;
$api->getLevel();
I finally have found the solution for the question, of course with help of two of you.
I think the solution need a bit more clarification.
The best way to do that is to post the code which worked for me, here it is,
// Main method to post user info
function getLevel() {
// Check for required parameters
if (isset($_POST["username"])) {
// Put parameters into local variables
$usernameQ = $_POST["username"];
// fire the query
$stmt = $this->db->prepare('SELECT level_id, username, filename from mm_levels WHERE username=? ');
$stmt->bind_param("s", $usernameQ ) ;
$stmt->execute();
$arr = array();
$stmt->bind_result($lev_id,$username, $filename);
$i=0;
while ($stmt->fetch())
{
$arr[] = array( "filename" => $filename ); // <= this line was the last addition and did the trick
$i++;
}
$stmt->close();
sendResponse(200,json_encode($arr));
return true;
}
sendResponse(400, 'Invalid request');
return false;
} //getLevel
} //GetLevelAPI