I've got a PHP class which has 1 method for inserting data. Once I create my instance of the class, I'm not sure how to call the method. I've seen other questions about how to accomplish calling a method, but none deal with calling the method of a class instance.
My PHP is:
<?php
$servername = "localhost";
$username = "kevin";
$password = "ally";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert"))
{
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
}
class Dog
{
public $name = "Dog Name";
public $size = 0;
public $color = "255:255:255";
public $typeName = "type Name";
public $typeDescription = "type Description";
public function Dog($name, $size, $color, $type, $description){
$this->name = $name;
$this->size = $size;
$this->color = $color;
$this->typeName = $type;
$this->typeDescription = $description;
}
public function InsertDog(){
$query = "SELECT Id from tbl_type WHERE Name = $typeName";
$result = mysqli_query($conn, "INSERT INTO tbl_type($this->typeName, $this->$typeDescription)") or die("Query fail: " . mysqli_error());
$result2 = mysqli_query($conn, "INSERT INTO tbl_Dog($this->$name, $this->$size, $this->$color, $query)") or die("Query fail: " . mysqli_error());
}
public function UpdateDog(){
}
}
?>
And my form:
<form action="index.php" method="post">
Dog Name:<br />
<input name="txtName" type="text" /><br />
<br />
Size:<br />
<input name="txtSize" type="text" /><br />
<br />
Color:<br />
<input name="txtColor" type="text" /><br />
<br />
type Name:<br />
<input name="txttype" type="text" /><br />
<br />
type Description:<br />
<input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br />
<br />
<input name="btnInsert" type="submit" value="Insert" />
</form>
How can I call the InsertDog() method for the $Dog instance?
Simply use:
...
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
$Dog->InsertDog();
:)
You can simply have all your codes in one file (index.php) and then you can use:
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
$Dog->InsertDog();
Or second solution is add ajax to your code. So link jquery:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
edit
<input name="btnInsert" type="submit" value="Insert" />
to
<input name="btnInsert" type="submit" value="Insert" id="buttonId" />
and add:
<script>
$( document ).ready(function() {
$( "#buttonId" ).click(function() {
$.ajax({
type: "POST",
url: "index.php",
data: { txtName: "DogsName", txtSize: "DogSize", txtColor: "color", txttype: "type", txtDescription: "dscr"v}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
url to your index.php must really server/index.php - so if you use localhost, it must be http://localhost/index.php
I didn't test it, but it should works
Related
when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>
I am new to angularjs. When I try to insert data into database through angularjs, neither it reports error nor gives any result.
I have included 3 files here. I am trying to insert data with this code.
index.html
<form name="add_product" method="post">
<div class="lable_left">
<p>First Name :</p>
<p>Last Name :</p>
<p>Address :</p>
<p>Age :</p>
<p>Department :</p>
</div>
<div class="input_left">
<p><input type="text" name="fname" ng-model="fname"></p>
<p><input type="text" name="lname" ng-model="lname"></p>
<p><input type="text" name="address" ng-model="address"></p>
<p><input type="text" name="age" ng-model="age"></p>
<p><input type="text" name="dept" ng-model="dept"></p>
<input type="hidden" name="eid" ng-model="eid" />
<input type="button" name="submit_product" ng-show='add_prod' value="Submit" ng-click="product_submit()" class="submitbutton">
<input type="button" name="update_product" ng-show='update_prod' value="Update" ng-click="update_product()" class="submitbutton">
</div>
</form>
db.php
<?php
include('config.php');
switch($_GET['action']) {
case 'add_product' :
add_product();
break;
}
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$fname = $data->fname;
$lname = $data->lname;
$address = $data->address;
$age = $data->age;
$dept = $data->dept;
print_r($data);
$qry = 'INSERT INTO employee (efname,elname,eaddress,eage,edept) values ("' . $fname . '","' . $lname . '",' .$address . ','.$age.','.$dept.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
?>
controller.js
var listApp = angular.module('listpp', []);
listApp.controller('PhoneListCtrl', function ($scope,$http) {
/** function to get detail of product added in mysql referencing php **/
$scope.get_product = function() {
$http.get("db.php?action=get_product").success(function(data)
{
//$scope.product_detail = data;
$scope.pagedItems = data;
});
}
/** function to add details for products in mysql referecing php **/
$scope.product_submit = function() {
$http.post("db.php?action=add_product",
{
'efname' : $scope.fname,
'elname' : $scope.lname,
'eaddress' : $scope.address,
'eage' : $scope.age,
'edept' : $scope.dept
}
)
.success(function (data, status, headers, config) {
$scope.get_product();
})
.error(function(data, status, headers, config){
});
}
Any help will be highly appreciated,
Thanks
What I want to do is save all the data - after the user has filled all the forms - using Ajax and PDO.
My problem is that my Ajax won't send to user.php. I got an error in the console after I click the button says "data is not defined". Can anyone help me fix my code?
HTML
<form method="post" enctype="multipart/form-data">
<img id="picture" data-src="#" /> <br />
<input type='file' name="image" id="imgInp" accept="image/*" /><br />
Name: <input type="text" id="name" name="name" /><br />
Age: <input type="text" id="age" name="age" /><br />
Address: <input type="text" id="address" name="address" /><br />
<input type="radio" name="gender" id="gender" value="male" />Male
<input type="radio" name="gender" id="gender" value="Female" />Female<br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Ajax
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
data.name = $('#name').val();
data.age = $('#age').val();
data.gender = $('#gender').val();
data.address = $('#address').val();
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "user.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
</script>
user.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
?>
Looks like you forgot to define your data variable.
var data = {};
data.name = $('#name').val();
You should initialize your data object as followed var data = {};.
Also consider to rename data to something like param. Just to not interfere with reserved names within the $.ajax({});-function. It's just a tip from a developer perspective.
What I'm trying to do is to make an installation file where the user enters the database, username, password, and host as a first step in a php system installation.
Also I want to create a page where user give his model page name and variable names ( $name,$email ) then automatically create a file with php code like
class Admin extends MyBase
{
private $name,$email;
public function setName($v)
{
$this->name = $v;
}
public function setEmail($v)
{
$this->email = $v;
}
public function getName()
{
return $this->name;
}
public function getEmail()
{
return $this->email;
}
public function Insert()
{
$sql = "insert into
admin(name,email)
values('".$this->ms($this->name)."','".$this->ms($this->email)."')";
return $this->MyCommand($sql);
}
}
with code format.
Finally I can do a example
<?php
if (isset($_POST["Submit"])) {
$string = '<?php
$dbhost = "'. $_POST["dbhost"]. '";
$dbuname = "'. $_POST["dbuname"]. '";
$dbpass = "'. $_POST["dbpass"]. '";
$dbname = "'. $_POST["dbname"]. '";
$prefix = "'. $_POST["prefix"]. '";
$user_prefix = "'. $_POST["user_prefix"]. '";
$dbtype = "'. $_POST["dbtype"]. '";
?>';
$fp = fopen("config.php", "w");
fwrite($fp, $string);
fclose($fp);
}
?>
<form action="" method="post" name="install" id="install">
<p>
<input name="dbhost" type="text" id="dbhost" value="">
DB Host
</p>
<p>
<input name="dbuname" type="text" id="dbuname">
DB Username
</p>
<p>
<input name="dbpass" type="password" id="dbpass">
DB Pass </p>
<p>
<input name="dbname" type="text" id="dbname">
DB Name </p>
<p>
<input name="prefix" type="text" id="prefix">
DB Prefix</p>
<p>
<input name="user_prefix" type="text" id="user_prefix">
Userprefix</p>
<p>
<input name="dbtype" type="text" id="dbtype">
DB Type </p>
<p>
<input type="submit" name="Submit" value="Install">
</p>
</form>
I was trying to create a login page, but it doesn't seem to work. When I click Login/Signup, a popup shows. I enter details and click login. Nothing happens. I try to signup, still nothing happens.
My homepage
<HTML>
<HEAD>
<TITLE>Experiment on Social Network</TITLE>
<script src = "jscript.js"></script>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
<script type = "text/javascript">
window.onload = function()
{
document.getElementById("LoginBtn").onClick = sendRequest("login.php");
document.getElementById("SignBtn").onClick = sendRequest("Signup.php");
};
</script>
</HEAD>
<BODY bgcolor = "black" text = "white" alink = "blue" vlink = "cyan">
Home
<div id = "responseOutput">
<a id = "logSign_pop" href = "#logSign">Login or Signup</a>
<div class = "popup">
<h1>Welcome Guest!</h1>
<form action = "#">
<h3>Login Here</h3>
<label for = "user">Username</label>
<br />
<input type = "text" id = "uname" value = "" />
<br />
<label for = "password">Password</label>
<br />
<input type = "password" id = "pass" value = "" />
<br />
<input type="button" id = "LoginBtn" value="Log In" />
<a class="close" href="#close"></a>
</form>
<form action = "#">
<h3>Sign Up</h3>
<label for="firstName">First Name</label>
<br/>
<input type="text" id="firstName" value="" />
<br />
<label for="lastName">Last Name</label>
<br/>
<input type="text" id="lastName" value="" />
<br />
<label for="useName">UserName</label>
<br/>
<input type="text" id="useName" value="" />
<br />
<label for="email">Email</label>
<br/>
<input type="text" id="email" value="" />
<br />
<label for="pass">Password</label>
<br/>
<input type="password" id="pwd" value="" />
<br />
<input type="button" id = "SignBtn" value="Sign Up" />
<a class="close" href="#close"></a>
</form>
</div>
</div>
<br/>
<center>
<h1>Welcome to MaxZeroEdge Network</h1>
</center>
</BODY>
</HTML>
login.php
<?php
$logID = $_POST["uname"];
$pass = $_POST["pass"];
$login = 0;
$con = mysql_connect("localhost","admin","admin");
if (!$con)
{
die('Could not connect to database: '. mysql_error());
}
$db = mysql_select_db("logDat", $con);
if(!$db)
{
create_db();
}
$tb = "SELECT * from logDat";
$av = #mysql_query($tb);
if(!$av)
{
echo "Error creating database: " . mysql_error();
}
else
{
checkLogin();
}
function checkLogin()
{
//Checks if a particular value exists
$result = mysql_query("SELECT * FROM logDat");
//$passResult = mysql_query("SELECT password FROM logDat");
$check = $logID;
while($login == 0 && $row = mysql_fetch_array($result))
{
if($row["Username"] == $logID)
{
if($row["password"] == $logPass)
{
/*$login = 1;
$expire = 86400*7;
setcookie("user",$logID,$expire);*/
$_SESSION["userid1"] = $logID;
print "<message>Welcome $logID</message>";
//header("Location: Social Network.php"); // redirects
}
else echo "Incorrect Password.";
}
else echo "User doesn't exist.";
}
}
//Runs for the first time only. Creates the database
function create_db()
{
if (mysql_query("CREATE DATABASE logDat",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
//Runs for the first time only. Creates the table.
function create_table()
{
//Password varchar(20),
$user = "CREATE TABLE logDat
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARYKEY(personID),
Username varchar(20),
FirstName varchar(50),
LastName varchar(50),
Email varchar(100),
password varchar(20);
)";
mysql_query("INSERT INTO logDat(PRIMARYKEY, Username, FirstName, LastName, Email, password) VALUES(0, 'zero', 'Palash', 'Max', 'maxzeroedge#gmail.com', 'hellfire') ");
}
mysql_close($con);
?>
Remove javascript window.onload function
Use input type submit for button and add targated page to action
As:
<form action = "login.php" method='post'>
<input type="submit" id = "LoginBtn" value="Log In" />
Instead of
<form action = "#">
<input type="button" id = "LoginBtn" value="Log In" />
Same thing for Sugn Up portion