Insert Selected data in database - php

Basically I want to insert a Foreign key acc_id in patient_info table from account_info table.
I have managed to retrieve the data from my database. Now I want to insert it in another table as Foreign key. I have following code :
try {
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
How can I insert the value in the table?
this is the full code :
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$key = strip_tags($_REQUEST['key']);
$data = array();
switch($key)
{
// Add a new record to the technologies table
case "create":
// Sanitise URL supplied value
$acc_id = filter_var($_REQUEST['acc_id'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_fname = filter_var($_REQUEST['p_fname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_lname = filter_var($_REQUEST['p_lname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_gender = filter_var($_REQUEST['p_gender'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_condition = filter_var($_REQUEST['p_condition'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_emergencycontact = filter_var($_REQUEST['p_emergencycontact'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_birthdate = filter_var($_REQUEST['p_birthdate'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
try{
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
$stmt->bindParam(':acc_id', $acc_id, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record was added to the database'));
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
}
?>
I am getting this error:
ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
I am getting the error here which links back to the php file:
load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
.map(res => res.json())
.subscribe(data =>
{
this.items = data;
});
}
Solution: insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

I'm pretty sure you could improve your code by removing your while loop and instead go like :
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
Are you sure you're getting expected JSON (tried any var_dump of $data before printing it ?) ?
Isn't it just a simple problem with JavaScript ? Have you tried to use the data you're supposed to get in your JavaScript part ?
It might be a problem of setting headers inside your XMLHttpRequest, and JavaScript doesn't care and give you the JSON anyway...
Now obvious questions :
I can't see where you connect to your database. Are you connected ?
You're trying to insert an ID, does MySQL allow you to INSERT auto increment value ? (in which case, isn't acc_id an Int ?)
You're sending values through $_REQUEST, are you sure you're getting anything through $_REQUEST (btw, check $_GET and $_POST)
I hope it helps

Related

What could cause a PHP insert into a MYSQL database to wrongly insert data from another user into a row?

A student of mine was saving her score for a learning game to a MySQL database but somehow a different person's name ended up being stored in her database row. How is this possible? Here is the PHP for the insert.
// Get Configuration file
require "configenzymatic.php";
// Connect to your server
$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
///////////////////////////////////////////////////////
// Status Checker
///////////////////////////////////////////////////////
if ($_GET["status"]) {
echo "online";
exit;
}
///////////////////////////////////////////////////////
// Upload new score
///////////////////////////////////////////////////////
//set POST data as data to be checked and updated
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$level1right = $_POST['level1right'];
$level1wrong = $_POST['level1wrong'];
$level2right = $_POST['level2right'];
$level2wrong = $_POST['level2wrong'];
$level3right = $_POST['level3right'];
$level3wrong = $_POST['level3wrong'];
$level4right = $_POST['level4right'];
$level4wrong = $_POST['level4wrong'];
// check for email and set hash variable
$stm = $dbh->prepare("SELECT * FROM $tname WHERE email=?");
$stm->bindValue(1, $email, PDO::PARAM_STR);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$hashes = array($row['hash']);
$hash = $row['hash'];
$id = $row['id'];
foreach ($hashes as $hash) {
// If hash matches password, then...
if (password_verify($password, $hash)) {
// Everything is cool -- Insert the data into the database (update)
$stmt = $dbh->prepare("
UPDATE $tname
SET firstname = :firstname
, lastname = :lastname
, hash = :hash
, level1right = :level1right
, level1wrong = :level1wrong
, level2right = :level2right
, level2wrong = :level2wrong
, level3right = :level3right
, level3wrong = :level3wrong
, level4right = :level4right
, level4wrong = :level4wrong
WHERE email = :email
AND id = :id");
$stmt->execute(array($firstname, $lastname, $hash, $level1right, $level1wrong, $level2right, $level2wrong, $level3right, $level3wrong, $level4right, $level4wrong, $email, $id));
$affected_rows = $stmt->rowCount();
// check if row inserted
/* Return number of rows that were updated */
$count = $stmt->rowCount();
echo "$count";
}
}
}
The student inputted her name but someone else's name got inserted. I am totally baffled by this. Does anyone have any idea how this could occur? The person whose name was inserted in place of my student's added data at 12:30:44 today and my student added her data at 13:44:15. How did this data get mixed?
I'm not certain why you had your update wrapped in multiple loops, but it's entirely possible that users with the same password hash could exist, and (I think) would explain the behaviour you're seeing.
You are, presumably, looking to update the single user with the email and password submitted in the form? I assume you also have constraints on your table to ensure that email addresses are unique. So, you're grabbing the single user that matches that email, and checking their password. If it matches, update the single record with the same database ID. No loops!
// get password hash
$stm = $dbh->prepare("SELECT id, hash FROM $tname WHERE email=?");
$stm->execute([$_POST["email"]]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
$hash = $row['hash'];
$id = $row['id'];
if (!password_verify($_POST["password"], $hash)) {
// verification failed, do something to present an error to the user
die();
}
$stmt = $dbh->prepare(
"UPDATE $tname
SET firstname=:firstname, lastname=:lastname,
level1right=:level1right, level1wrong=:level1wrong,
level2right=:level2right, level2wrong=:level2wrong,
level3right=:level3right, level3wrong=:level3wrong,
level4right=:level4right, level4wrong=:level4wrong
WHERE id=:id"
);
$stmt->execute([
":firstname" => $_POST["firstname"],
":lastname" => $_POST["lastname"],
":level1right" => $_POST["level1right"],
":level1wrong" => $_POST["level1wrong"],
":level2right" => $_POST["level2right"],
":level2wrong" => $_POST["level2wrong"],
":level3right" => $_POST["level3right"],
":level3wrong" => $_POST["level3wrong"],
":level4right" => $_POST["level4right"],
":level4wrong" => $_POST["level4wrong"],
":id" => $id
]);
$count = $stmt->rowCount();
echo "$count";
Also note that using named parameters in PDO requires the use of an associative array. Not sure how your original code would update anything at all without that.

insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

Thank you for being here!
i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key
I am getting this error :
In my localhost i can see the value it's suppose to return.
And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null
Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }
php file :
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try{
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// Return data as JSON
echo json_encode($data);
var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
$stmt->bindParam(':data', $acc_id, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record was added to the database'));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:
<?php
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try {
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// You do not need to return response from here
// echo json_encode($data);
// var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
// the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
// notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
// so, I just added some dummy data.
$p_fname = 'Patient first name';
$p_lname = 'Patient last name';
$p_gender = 'm';
$p_condition = 'condition';
$p_birthdate = '1999-01-01';
$p_emergencycontact = 'Contact';
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
// You do not have any $acc_id variable in your code. To get data from your fetch you need to do
// like this:
$stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR);
$stmt->execute();
header('Access-Control-Allow-Origin: *');
// If you want to get the acc_id in your client side through the AJAX call, combine both
// mesage and data in the same JSON object.
echo json_encode(
array(
'message' => 'Congratulations the record was added to the database'
'data' => $data
)
);
} catch(PDOException $e) {
// make sure to send the proper status code
http_response_code(500);
// even error should be sent back as in json so that your javascript client can
// easily parse it
echo json_encode(
array(
'error' => $e->getMessage()
)
);
}
?>

Select returning empty query

I'm trying to select data where by acc_id
What I get in my localhost: []
However, when I set a specific acc_id i get the correct row is there something in my syntax?
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
$data = array();
// Attempt to query database table and retrieve data
try {
$acc_id = $pdo->prepare('SELECT acc_id FROM account_info');
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = "$acc_id"');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It seems like you want to use the prepared statement but instead executing your query instantly. If you want to bind the value to your query use something like this:
$acc_id = // get the $acc_id value from somewhere you want
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = ?');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// Assign each row of data to associative array
$data[] = $row;
}
Example with using a placeholder
Instead of executing your statement with the array of params, you could also use the bindValue() or the bindParam() method:
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = :acc_id');
$stmt->bindValue(':acc_id', $acc_id);
$stmt->execute();
// everything else works as previous
The difference between these two methods is written in docs:
bindValue():
Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
bindParam():
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Receiving Error Message in ionic App from PHP file on Post Request

It is required to add the product to the MySql Database (remote)
by the ionicApp. There is a Product Page. When submit is pressed, the post method is called from the ionicApp "Product.ts" page by function createEntry().
The record has been created successfully if there is no constraint error with the help of a PHP file named manage_products.php.
In the ionic app if(data.status === 200) is true then the body get executed. But there is no way if the record has been created or not. if there is some problem, for example, some null constraint (Db side) then it is only via the Chrome network tab that I come to know about some constraint error. Is there any way to receive error text from the PHP file in the ionic App.
Here is the function to createEntry called from ionicApp "Product.ts"
createEntry()
{
let id = "0000";
let name = "Some Product";
let description = "Some Product description";
let manufacturer_name = "manufacturer_name";
let weight = "some weight is here";
let weight_unit = "kg";
let halal_status = "HALAL";
let body : string = "key=create&id=" + id + "&name=" + name + "&description=" + description + "&manufacturer_name=" + manufacturer_name + "&weight=" + weight + "&weight_unit=" + weight_unit + "&halal_status=" + halal_status ,
type : string = "application/x-www-form-urlencoded; charset=UTF-8",
headers : any = new Headers({ 'Content-Type': type}),
options : any = new RequestOptions({ headers: headers }),
url : any = this.baseURI + "manage_products.php";
this.http.post(url, body, options)
.subscribe((data) =>
{
// If the request was successful notify the user
if(data.status === 200)
{
// this.hideForm = true;
console.log(`Congratulations the technology: ${name} was successfully added`);
console.log('successfully added the record. .......');
}
// Otherwise let 'em know anyway
else
{
// this.sendNotification('Something went wrong!');
console.log('Couldnt add the record.....xxx');
}
});
}
The above code is calling the PHP file. Here is the code for the PHP file.
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'username';
$pwd = 'password';
$db = 'name-of-database';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$key = strip_tags($_REQUEST['key']);
$data = array();
// Determine which mode is being requested
switch($key)
{
// Add a new record to the technologies table
case "create":
// Sanitise URL supplied values
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
// Attempt to run PDO prepared statement
try {
$sql = "INSERT INTO Products(id,name,manufacturer_name,weight,weight_unit,halal_status,description) VALUES(:id, :name, :manufacturer_name, :weight, :weight_unit, :halal_status, :description)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $manufacturer_name, PDO::PARAM_STR);
$stmt->bindParam(':weight', $weight, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $weight_unit, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $halal_status, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record ' . $name . ' was added to the database'));
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
// Update an existing record in the technologies table
case "update":
// Sanitise URL supplied values
/*
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$recordID = filter_var($_REQUEST['recordID'], FILTER_SANITIZE_NUMBER_INT);
*/
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
// Attempt to run PDO prepared statement
try {
$sql = "UPDATE Products SET id = :id, name = :name,manufacturer_name = :manufacturer_name,weight = :weight,weight_unit = :weight_unit,halal_status = : halal_status, description = :description WHERE id = :id";
$stmt = $pdo->prepare($sql);
/*
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
*/
$stmt->bindParam(':id', $name, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $description, PDO::PARAM_STR);
$stmt->bindParam(':weight', $name, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $name, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $description, PDO::PARAM_STR);
$stmt->bindParam(':description', $name, PDO::PARAM_STR);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was updated');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
// Remove an existing record in the technologies table
case "delete":
// Sanitise supplied record ID for matching to table record
$recordID = filter_var($_REQUEST['id'], FILTER_SANITIZE_NUMBER_INT);
// Attempt to run PDO prepared statement
try {
$pdo = new PDO($dsn, $un, $pwd);
$sql = "DELETE FROM Products WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was removed');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
}
?>
you can use the alertcontroller or toastcontroller and display the error message by adding a catch after you have subscribed to the data...like this
catch((err)=>{
this.AlertMessage("error", err);
});

jQuery Ajax - $sql is an object Error

UPDATE at bottom of question
I'm getting the error:
Warning: mysqli_query() expects parameter 2 to be string, object
given
Questions about this are incredibly common on Stack Overflow - my apologies in advance. I haven't been able to find a good answer for my specific problem. If there is a thread that addresses this, please let me know.
Here is my Ajax code:
$.ajax({
url: "get.php",
type: "post",
datatype: "json",
data:{ ajaxid: altCheck }, //this is an integer passed to MySQL statement
success: function(response){
console.log(response);
},
error: function(){
console.log("test");
}
});
get.php
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
var_dump($value); //checking to see what $value is at this point
$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?");
$sql->bind_param("s",$value);
//THIS LINE THROWS THE ERROR
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
?>
The fourth line of code var_dump($value); outputs string(0).
UPDATE: MySQLi
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
$query = $db->prepare('SELECT * FROM table WHERE screeningId = ?');
$query->bind_param('s', $_GET[$value]);
$query->execute();
if ($result = mysqli_query($db, $query)) {
while ($url = mysqli_fetch_object($result, 'imageURL')) {
echo $url->info()."\n";
}
}
?>
Screenshot of MySQL table data columns:
EDIT
Okay... 8 edits spent on mysqli... Enought!
Here is how I DO using PDO. And it WILL work first shot.
I have a separate file for the database connection info.
dbconnection.php:
(The advantage of the separate definition file is one place to update the user password when needed.)
<?php
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[DATABASE_NAME];host=127.0.0.1';
$user = '[DATABASE_USER]';
$password = '[USER_PASSWORD]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
?>
Now in your PHP files where a database request has to be done, include the PDO definition file, the just request what you want:
<?php
include('dbconnection.php');
// JUST TO DEBUG!!!
$_REQUEST['ajaxid'] = "1";
// Database request.
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
$stmt->bindParam(1, $_REQUEST['ajaxid']);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die;
}
// Looping through the results.
$result_array =[];
while($row=$stmt->fetch()){
array_push($result_array,$row['imageURL']);
}
// The result array json encoded.
echo json_encode($result_array);
?>
Since you are using mysqli_* all other place in your project, update your get.php as below.
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
//var_dump($value); //checking to see what $value is at this point
$sql = "SELECT * FROM table WHERE screeningId = '$value'";
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
EDIT
With respect to bind param with mysqli,
<?php
$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');
$sql = 'SELECT * FROM table WHERE screeningId = ?';
$stmt = $conn->prepare($sql);
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$stmt->bind_param('s', $value);
$stmt->execute();
$res = $stmt->get_result();
$temp = array();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
Select Data With PDO in get.php:
<?php
if( isset($_POST['ajaxid']) ) {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table WHERE screeningId = :screeningId");
$stmt->execute(array(':screeningId' => $_POST['ajaxid']));
$row = $stmt->fetch();
}
?>
You configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $conn object:
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories