Unable to save form data to sql table using php - php

I am trying to save a form data into sql table using php. Eventhough I am not getting error while submit, data is not showing up in table.
My submit button name is input_submit
Here is my code:
if(isset($_POST['input_submit'])){
include 'dbConnection.php';
include 'saveData.php';
}
dbConnection.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
include_once $path . '/wp-config.php';
class ConnectDB{
private $servername;
private $username;
private $password;
private $dbname;
protected function connect(){
$this->servername ="localhost";
$this->username ="root";
$this->password ="";
$this->dbname ="testdb";
$conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);
if($conn -> connect_error) {
die("connection failed:".$conn-> connect_error);
}
return $conn;
}
}
?>
saveData.php:
<?php
class saveinput extends ConnectDB {
public function Savein(){
$date = $_POST['date'];
$entry_type = $_POST['entry_type'];
$amount = $_POST['amount'];
$sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount)
VALUES(?, ?, ?)");
$sql->bind_param("sss",$date, $entry_type, $amount);
$sql->execute();
if ($sql->execute()) {
echo "success";
} else {
echo "failed";
}
}
}
?>
while submit, form is getting submitted. But when I check the db table, nothing is showing up. I am not understanding whats wrong here. Can someone guide me please.

You should call your "connect" method inside your Savein method in a var. So, your Savein method should be:
public function Savein(){
$conn = parent::connect(); // This is the only thing i've added
$date = $_POST['date'];
$entry_type = $_POST['entry_type'];
$amount = $_POST['amount'];
$sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount)
VALUES(?, ?, ?)");
$sql->bind_param("sss",$date, $entry_type, $amount);
if ($sql->execute()) {
echo "success";
} else {
echo "failed";
}
}

Related

Issue with mysqli in PHP Warning: mysqli_stmt_prepare() expects parameter 1

I have been looking at this code for a while and can't figure out where the problem is.
I am new to coding in general, but especially new to CRUD and SQL. I want to create a prepared statement here to use variables instead of exact values. I don't understand where the issue comes from
I have a Databasetools.php
<?php
class DatabaseTools
{
//private $user = $_SESSION['userId']; // these get called when the object gets created
//private $userEmail = $_SESSION['emailUser'];
public function __construct($Name)
{
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "supersecretpassword";
$dbPort = "3306";
$this->name = $Name;
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $this->name, $dbPort);
$stmt = mysqli_stmt_init($conn);
if(!$conn)
{
die("connection faild: ".mysqli_connect_error());
}
}
public function lookup($dBName, $Row, $Column)
{
//$sql = "SELECT ".$Column." FROM ".$dBName." WHERE ".$Row.";";
$sql = "SELECT ? FROM ? WHERE ?;";
if(!mysqli_stmt_prepare($stmt, $sql))
{
echo "False";
}
else
{
mysqli_stmt_bind_param($stmt, "sss", $column, $dBName, $Row);
mysqli_stmt_execute($stmt);
$result = mysli_stmt_get_result($stmt);
echo $result;
}
// try to connect to the database
}
public function setCell($Database, $Row, $Column)
{
}
public function disconnect($dBName)
{
}
public function echotest()
{
}
}
?>
And I am using a page to check if the code is working
<?php
require "Model/php/databaseTools.php";
$loginData = new databaseTools("loginsystem");
$loginData->lookup("loginsystem","*","*");
?>
Thanks so much if you could point me in the write direction.
Are you sure you have $stmt value in the lookup function?
Try to add it as one of the parameters, something like this:
public function lookup($dBName, $stmt, $Row, $Column)
and then call it also with $stmt parameter:
$loginData->lookup("loginsystem", <stmt> ,"*","*");

Php Class inside included file not found

I was trying to follow this tutorial to make a simple login and registration for Android application with MySql. The Android app runs fine until it hit an error when accessing the database (account register).
When I tried to access the php application to make sure that the error is in the Android app, I got this error:
Fatal error: Class 'DbConnect' not found in C:\xampp\htdocs\AndroidLogin\include\user.php on line 12
I'm sure that db.php is already included in user.php. These are the codes I used from the tutorial: The first one is index.php
//index.php
<?php
require_once 'include/user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
// Instance of a User class
$userObject = new User();
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}
// User Login
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
Next, config.php
//config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "androidlogin");
?>
This one is db.php
// db.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
And the last one is user.php
// user.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($username, $password){
$query = "select * from " . $this->db_table . " where username = '$username' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function createNewRegisterUser($username, $password, $email){
$query = "insert into users (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
My directory looks like this:
AndroidLogin
|index.php
|include
|config.php
|db.php
|user.php
Do I miss something?
Usually, call the file like the class that you declare in it. In WAMP usually it gives some issues, i suggest to you to rename db.php in DbConnect.php
Make a default (empty) constructor in DbConnect, and make a simple method that would echo something. Try to make new DbConnect instance call that method from User class?

Sql Statement from PHP isnt inserting into Database but doesnt give an error

Thanks to this site i could manage to solve my problems, but my statement isnt going through on my database, but when i copy it and paste it directly to my database, it inserts without any problem. Here my code:
<?php
$ip = "***"; //MySQL Server IP
$user = "***"; //MySQL user
$pw = "***"; //MySQL password
$db = "***"; //Database
$sql_filter = "";
$con = mysqli_connect($ip, $user, $pw, $db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function register()
{
$username = $_POST[username];
$vorname = $_POST[vorname];
$nachname = $_POST[nachname];
$geschlecht = $_POST[geschlecht];
$geburtsdate = $_POST[geburtsdatum];
$password = $_POST[password];
$email = $_POST[email];
if($email!="" and $password!="" and $username!="" and $password==$_POST["password_confirm"])
{
$sql_filter = "INSERT INTO `tblUser`(`UserID`, `UserName`, `Vorname`, `Nachname`, `EMail`, `Geschlecht`,`Password`) VALUES ('','$username','$vorname','$nachname','$email','$geschlecht','$password')";
$_SESSION['filter'] = $sql_filter;
$page_query = mysqli_query($con, $_SESSION['filter']);
$page_nums = mysqli_num_rows($page_query);
//header('Location: index.php');
echo $sql_filter;
echo $_SESSION['filter'];
}
else
{
header('Location: 404.html');
}
}
if(isset($_POST['submit']))
{
register();
}
mysqli_close($con);
?>
I think the problem is your $con is undefined in the function register(). So add this in the beginning of your function :
function register()
{
global $con;
... // the rest of your function
}

Call to member function query() on Null [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
So just trying to make a simple register/login form which i have done before, but not for hell can i figure out why this is happening. my code looks like the below.
Ive commented out the error above the line that it says its occurring.
<?php
class connection{
private $hostname = "localhost";
private $username = "root";
private $password = "";
private $database = "test";
private $conn;
public function __construct(){
$conn = new mysqli($this->hostname, $this->username, $this->password, $this->database)or die("MySQL Connection Error");
}
public function getConn(){
return $this->conn;
}
}
class queries{
private $conn;
public function __construct($conn){
$this->conn = $conn;
}
public function checkUser($username, $email){
$query = "SELECT * FROM users WHERE username = '$username' OR email = '$email'";
//Call to a member function query() on null in C:\xampp\htdocs\i\functions.php on line 28
$result = $this->conn->query("$query");
return $result;
}
public function insertUser($activated, $activation_code, $firstname, $lastname, $username, $password, $email){
$query = "INSERT INTO users (activated, activation_code, firstname, lastname, username, password, email)
VALUES ('$activated', '$activation_code', '$firstname', '$lastname', '$username', '$password', '$email')";
$result = $this->conn->query("$query");
}
}
Seems Simple enough right.. now heres my php code on the page thats being used (register.php).
if (isset($_POST['register'])) {
include 'functions.php';
$connection = new connection();
$query = new queries($connection->getConn());
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = sha1($_POST['password']);
$user = $query->checkUser($username, $email);
if ($user->num_rows > 0) {
echo "User Exists";
}else{
echo "User Does not Exist";
}
}
Your code seems correct, except in the constructor of your connection class, you've forgot to use the $this, change it to something like the following:
public function __construct() {
$this->conn = new mysqli($this->hostname, $this->username, $this->password, $this->database)or die("MySQL Connection Error");
}

Registration with PDO/PHP doesn't work

I've got a problem through build a registration system. I don't know where is the problem, because I'm a beginner in PHP OOP.
Here's my registration class:
<?php
/*
*=======================
* REGISTRATION CLASS !!!
* ======================
*/
include_once '/../core/registration.php';
include_once '/../core/db_connect.php';
class registration {
private $db;
function __construct() { /* Connecting with MySQL */
$this->db = new db_connect();
$this->db = $this->db->connect();
} /* End of connection */
function registration($username, $password1, $password2, $email, $date) {
if(!empty($username) && !empty($password1) && !empty($password2) && !empty($email)) {
$q = $this->db->prepare("INSERT INTO users(username, password, email, date, logged, admin) VALUES (?, ?, ?, ?, ?, ?)");
$q->bindParam(1, $username);
$q->bindParam(2, $password1);
$q->bindParam(3, $email);
$q->bindParam(4, $date);
$q->bindParam(5, '0');
$q->bindParam(6, '0');
$q->execute();
}
}
}
?>
Here is a file, that is running, when user clicks on 'register' button:
<?php
include_once '/../classes/registration.php';
if(isset($_POST['regUser'])) {
$username = $_POST['regUsername'];
$pass1 = $_POST['regPassword1'];
$pass2 = $_POST['regPassword2'];
$email = $_POST['regEmail'];
$date = date("Y-m-d H:i:s");
$obj = new registration();
$obj->registration($username, $password1, $password2, $email, $date);
}
?>
For safety, I'll put also a connection file:
<?php
class db_connect {
function connect() {
return new PDO("mysql:host=127.0.0.1;dbname=oop", "root", "");
}
}
?>
It's one of the most common "error" with PDO.
With bindParam, you can only pass variables, not values.
In your registration() method, replace:
$q->bindParam(5, '0');
$q->bindParam(6, '0');
By:
$q->bindValue(5, '0');
$q->bindValue(6, '0');
With bindValue you can pass values and variables.
You can read the PHP manual for more info (here and here).

Categories