Based on : http://www.raywenderlich.com/2941/how-to-write-a-simple-phpmysql-web-service-for-an-ios-app
My database looks like this : id | rw_promo_code_id | email_id | device_id | redeemed_time
I try this in the index.php:
// Check for required parameters
if (isset($_POST["rw_app_id"]) && isset($_POST["code"]) && isset($_POST["email_id"]) && isset($_POST["device_id"]) ) {
...........
// Add tracking of redemption
$stmt = $this->db->prepare("INSERT INTO rw_promo_code_redeemed (rw_promo_code_id, email_id, device_id) VALUES (?, ?, ?)");
$stmt->bind_param("is", $id, $email_id, device_id);
$stmt->execute();
$stmt->close();
IF I REMOVE && isset($_POST["device_id"]) and make this line
$stmt = $this->db->prepare("INSERT INTO rw_promo_code_redeemed
(rw_promo_code_id, email_id, device_id) VALUES (?, ?, ?)");
to
$stmt = $this->db->prepare("INSERT INTO rw_promo_code_redeemed
(rw_promo_code_id, email_id) VALUES (?, ?)");
I GET THE EMAIL CORRECTLY IN THE DATABASE OF COURSE, BUT NOT THE DEVICE ID
How can I get the the both values (device_id and email_id) to display in the database and not only one ?
I use this in the app (there is no problem with this)
NSString *emailadrress = email.text;
NSURL *url = [NSURL URLWithString:#"http://localhost:8888/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"1" forKey:#"rw_app_id"];
[request setPostValue:code forKey:#"code"];
[request setPostValue:emailadrress forKey:#"email_id"];
[request setPostValue:#"23131" forKey:#"device_id"];
[request setDelegate:self];
[request startAsynchronous];
EDIT : HERE IS THE ORGINAL FUNCTION:
function redeem() {
// Check for required parameters
if (isset($_POST["rw_app_id"]) && isset($_POST["code"]) && isset($_POST["device_id"])) {
// Put parameters into local variables
$rw_app_id = $_POST["rw_app_id"];
$code = $_POST["code"];
$device_id = $_POST["device_id"];
// Look up code in database
$user_id = 0;
$stmt = $this->db->prepare('SELECT id, unlock_code, uses_remaining FROM rw_promo_code WHERE rw_app_id=? AND code=?');
$stmt->bind_param("is", $rw_app_id, $code);
$stmt->execute();
$stmt->bind_result($id, $unlock_code, $uses_remaining);
while ($stmt->fetch()) {
break;
}
$stmt->close();
// Bail if code doesn't exist
if ($id <= 0) {
sendResponse(400, 'Invalid code');
return false;
}
// Bail if code already used
if ($uses_remaining <= 0) {
sendResponse(403, 'Code already used');
return false;
}
// Check to see if this device already redeemed
$stmt = $this->db->prepare('SELECT id FROM rw_promo_code_redeemed WHERE device_id=? AND rw_promo_code_id=?');
$stmt->bind_param("si", $device_id, $id);
$stmt->execute();
$stmt->bind_result($redeemed_id);
while ($stmt->fetch()) {
break;
}
$stmt->close();
// Bail if code already redeemed
if ($redeemed_id > 0) {
sendResponse(403, 'Code already used');
return false;
}
// Add tracking of redemption
$stmt = $this->db->prepare("INSERT INTO rw_promo_code_redeemed (rw_promo_code_id, device_id) VALUES (?, ?)");
$stmt->bind_param("is", $id, $device_id);
$stmt->execute();
$stmt->close();
// Decrement use of code
$this->db->query("UPDATE rw_promo_code SET uses_remaining=uses_remaining-1 WHERE id=$id");
$this->db->commit();
// Return unlock code, encoded with JSON
$result = array(
"unlock_code" => $unlock_code,
);
sendResponse(200, json_encode($result));
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
EDIT: The error
PHP Warning: mysqli_stmt::bind_param() [<a
href='mysqli-stmt.bind-param'>mysqli-stmt.bind-param]:
Number of elements in type definition
string doesn't match number of bind
variables in
/Applications/MAMP/htdocs/index.php on
line 134
which is :
$stmt = $this->db->prepare("INSERT
INTO rw_promo_code_redeemed
(rw_promo_code_id, device_id,
email_id) VALUES (?, ?, ?)");
$stmt->bind_param("is", $id,
$device_id, $email_id);
got you...
you are missing value type for third variable.
$stmt = $this->db->prepare("INSERT INTO rw_promo_code_redeemed (rw_promo_code_id, device_id, email_id) VALUES (?, ?, ?)"); $stmt->bind_param("iss", $id, $device_id, $email_id);
change "is" to "iss" or "iis" any one required. you can get further info about bind_param on
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Related
I have an app that is written using procedural PHP. I've created an insert page where I take a buck of addresses and pass them as an array and insert them in the database. There I have the id of the row and then an orderId, the address type, and the address. Now I want to be able to update a specific one. Until now I've come up with the following:
// update new supplier order
function updateSupplierOrder($conn, $orderDate, $datePickup, $dateDelivery, $timePickup, $timeDelivery, $car, $carType, $goodsDescription, $paletChange, $paletNo, $supplier, $orderObservation, $paymentDate, $value, $addressPickup, $addressDelivery, $userid, $orderID) {
$sql1 = "UPDATE suppliersOrders SET supplierId = ?, date = ?, datePickup = ?, timePickup = ?, goodsDescription = ?, dateDelivery = ?, timeDelivery = ?, carType = ?, carNo = ?, paletChange = ?, paletNo = ?, value = ?, invoice = ?, observations = ?, operator = ? WHERE id = ?;";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header ("location: ../suppliersOrders?error=failedupdateorder");
exit();
}
mysqli_stmt_bind_param($stmt1, "isssssssisisssii", $supplier, $orderDate, $datePickup, $timePickup, $goodsDescription, $dateDelivery, $timeDelivery, $carType, $car, $paletChange, $paletNo, $value, $paymentDate, $orderObservation, $userid, $orderID);
mysqli_stmt_execute($stmt1);
mysqli_stmt_close($stmt1);
for ($i=0; $i<count($addressPickup); $i++) {
$address = $addressPickup[$i];
$type = '1';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
for ($i=0; $i<count($addressDelivery); $i++) {
$address = $addressDelivery[$i];
$type = '2';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
header("location: ../suppliersOrders-edit.php?id=$orderID");
}
But this will update all the addresses of an order and a type. How can I update based on the id from the table, this will make sure that the right address is updated.
Help would be appreciated.
I found a solution to the issues. The simplest way to be able to update the row that I needed was to add the id value from the row in an array and do the update based on the WHERE clause that had the id value. This way I was able to update just the needed value/row.
After executing INSERT statement there is no single error thrown and my database table is empty ,someone help please!
Service file for calling INSERT statement
roomservice.php
<?php
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
if(isset($_POST['hotelName']) && isset($_POST['hasTV']) &&
isset($_POST['beds']) && isset($_POST['price'])){
$roomName = $_POST['hotelName'];
$hasTV = $_POST['hasTV'];
$beds = $_POST['beds'];
$price = $_POST['price'];
echo addRoom($roomName,$hasTV,$beds,$price);
}
function addRoom($hotelName, $hasTV, $beds , $price){
global $conn;
$rarray = array();
$stmt = $conn->prepare("INSERT INTO rooms (hotelname, hastv, beds, price) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sss", $hotelName, $hasTV, $beds , $price);
if($stmt->execute()){
$rarray['sucess'] = "okej";
}else{
$rarray['error'] = "Database connection error";
}
return json_encode($rarray);
}
?>
Angular component file where i call the service file with data passed through form.
addroom.component.ts
public addRoom() {
const body = new HttpParams()
.set('hotelname', this.roomForm.value.hotelName)
.set('hastv', this.roomForm.value.hasTV)
.set('beds', this.roomForm.value.beds)
.set('price', this.roomForm.value.price);
console.log(body.toString());
this._api.post('roomservice.php', body.toString()).subscribe((data: any) => {
console.log(data);
// localStorage.setItem('token', JSON.parse(data['_body']).token);
this._router.navigate(['./']);
}, (error) => {
const obj = JSON.parse(error['_body']).error;
const element = <HTMLElement> document.getElementsByClassName('alert')[0];
element.style.display = 'block';
element.innerHTML = obj.split('\\r\\n').join('<br/>').split('\"').join('');
});
}
}
rooms table
client response
You're trying to pass 4 arguments to the bind function but you have entered only 3 parameters. That's why its not working.
The solution is to change these two lines:
$stmt = $conn->prepare("INSERT INTO rooms (hotelname, hastv, beds, price) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sss", $hotelName, $hasTV, $beds , $price);
to:
$stmt = $conn->prepare("INSERT INTO `rooms` (`hotelname`, `hastv`, `beds`, `price`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $hotelName, $hasTV, $beds , $price);
I have two tables users And requests. Users table has columns: id, username, password and town. I can insert data in users successfully. requests table has: id, user_id, product_name, proposed_price and request_description, where user_id is a foreign key referencing to id from users table. The problem is that insert data fails in requests table which has user_id as a foreign key. I get an error:
Undefined variable: user_id and mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement on line : $qry->bind_param("i", $user_id);
This function is supposed to be used in insertion:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
$qry->bind_param("i", $id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
And below code calls above function:
<?php
include './DbHandler.php';
$db = new DBHandler();
// json response array
$response = array("error" => FALSE);
if ( isset($_POST['product_name']) && isset($_POST['proposed_price']) && isset($_POST['request_description']) ) {
// receiving the post params
$product_name = $_POST['product_name'];
$proposed_price =$_POST['proposed_price'];
$request_description =$_POST['request_description'];
// create a new request
$user = $db-User_request($product_name, $proposed_price, $request_description);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["proposed_price"] = $user["proposed_price"];
$response["user"]["request_description"] = $user["request_description"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "oops error occured!";
echo json_encode($response);
}
}
else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
Rewrite User_request() function accordingly:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = ? ");
$qry->bind_param("i", $user_id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("isss", $user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
Note: You supposed to use placeholder ? in prepare statement: $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' "); in place of '$user_id', since you have $qry->bind_param("i", $user_id).
Similar error in $stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);, replace "sss" with "isss".
You are looking for the string literal of '$user_id' here.
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
This is probably not what you want. You are also using named placeholders that are nowhere to be found in your query. I suggest reviewing the PDO docs.
I tried to make the update statement to be safety againts sql injection but its give me this erro Fatal error: Call to a member function bind_param() on a non-object on line 39
$pid = $_POST['pid'];
$pagetitle = $_POST['pagetitle'];
$linklabel = $_POST['linklabel'];
$keyword = $_POST['keyword'];
$descriere = $_POST['descriere'];
$data = $_POST['data'];
$pagebody = $_POST['pagebody'];
// Filter Function -------------------------------------------------------------------
function filterFunction ($var) {
$var = nl2br(htmlspecialchars($var));
$var = str_replace("/", "\\\\", $var);
$var = preg_replace("~/~", "\\\\", $var);
return $var;
}
$pagetitle = filterFunction($pagetitle);
$linklabel = filterFunction($linklabel);
$keyword = filterFunction($keyword);
$descriere = filterFunction($descriere);
$data = filterFunction($data);
$pagebody = filterFunction($pagebody);
// End Filter Function --------------------------------------------------------------
include_once "../conx.php";
// Add the updated info into the database table
$stmt = $con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
$stmt->execute();
$stmt->close();
line 39 is $stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
it is necessary to make this or i can revert to how it was before
$query = mysqli_query($con, "UPDATE pages SET pagetitle='$pagetitle', linklabel='$linklabel', pagebody='$pagebody', lastmodified='now()' WHERE id='$pid'") or die (mysqli_error($con));
Didn't this produce an error?
$con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
this should be
$con->prepare("UPDATE pages SET pagetitle=?, linklabel=?, keywords=?, description=?, pagebody=?, lastmodified=? WHERE id = ?");
Refer: http://dev.mysql.com/doc/refman/5.7/en/update.html
now you can proceed to bind parameters
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
I'm working on a new website at the moment and I have a bit of a problem.
I look if an item exist, if it does, it will execute an insert query. The insert query works but the problem is that the select query doesn't work
Class
public function doubt($event_id)
{
$exist = $this->conn->prepare("SELECT * FROM agenda WHERE id=?");
$exist->bind_param('s', $event_id);
$exist->execute();
$exist->get_result();
if($exist->num_rows != null)
{
$now = new DateTime();
$date = $now->getTimestamp();
$status = 2;
$stmt = $this->conn->prepare("INSERT INTO absence (user_id,event_id,status,ip,date) VALUES (?, ?, ?, ?, ?) ");
$stmt->bind_param('sssss', $_SESSION['user_session'], $event_id, $status, $_SERVER['REMOTE_ADDR'], $date);
$stmt->execute();
$stmt->close();
return true;
}
else
{
return false;
}
}