PHP PDO Statement inserting Null value to Db table - php

PHP PDO Statement inserting Null value to Db table
MY CODE:-
function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
$query = "INSERT INTO eco_product_descTemp(`blockdigms1`, `blockdigms2`, `blockdigms3`) values(:company_digms1,:company_digms2,:company_digms3)";
try {
$stmt = $this->conn->prepare($query);
$stmt->bindValue(":company_digms1", $company_digms1);
echo $company_digms2;
$stmt->bindValue(":company_digms2", $company_digms2);
echo $company_digms3;
$stmt->bindValue(":company_digms3", $company_digms3);
$stmt->execute();
var_dump($stmt->errorInfo());
$productid = $this->conn->lastInsertId();
return $productid;
} catch (PDOException $e) {
$e->getMessage();
}
}
When i am executing, it only insert null value with auto increment id.
Thanks in advance.

function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
$query = "INSERT INTO eco_product_descTemp (`blockdigms1`, `blockdigms2`, `blockdigms3`) values(:company_digms1,:company_digms2,:company_digms3)";
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(":company_digms1", $company_digms1);
echo $company_digms2;
$stmt->bindParam(":company_digms2", $company_digms2);
echo $company_digms3;
$stmt->bindParam(":company_digms3", $company_digms3);
$stmt->execute();
var_dump($stmt->errorInfo());
$productid = $this->conn->lastInsertId();
return $productid;
} catch (PDOException $e) {
$e->getMessage();
}
}
Try this one.
Just replacing bindValue with bindParam
You can check prepared-statements.php here.

I've left $fieldvalues in but i dont see what it is doing..
Here's my take on it:
function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
if (!empty($company_digms1) && !empty($company_digms2) && !empty($company_digms3))
{
$stmt = $this->conn->prepare("INSERT INTO `eco_product_descTemp` (`blockdigims1`, `blockdigims2`, `blockdigims3`) VALUES (?,?,?)");
$stmt->execute([$company_digms1, $company_digms2, $company_digms3]);
echo 'Inserted!';
} else {
echo 'make sure all fields have been filled in!';
}
}
So on the condition that if none of the fields are empty (NULL) then run the query. If one is empty (NULL) then run the make sure statement.

Related

insert postgis geometry with GET values

I'm trying to make an insert using ST_Makepoint with get values, but I run into 500 Error.
This is my php code:
<?php
try {
$user = 'user';
$dbh = new PDO('pgsql:host=localhost;dbname=userdb', $user);
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,?);");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], ST_SetSRID(ST_MakePoint($_GET['lat'], $_GET['long']),4326)))) {
print_r("OK");
} else {
print_r("Error");
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
If I run this query with pgAdmin, it runs well:
INSERT INTO table(id_a, id_b, geom) VALUES (1,1,ST_SetSRID(ST_MakePoint(2, 2),4326));
Do you know how to fix the problem in php code?
I solved in this way:
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,ST_SetSRID(ST_MakePoint(?, ?),4326));");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], $_GET['lat'], $_GET['long']))) {
print_r("OK");
} else {
print_r("Errore");
}

Create foreach for a value that exists twice

I have the following statement which SELECTs ProductName and Quantity from the orderDetails table. See below:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
$_POST['ProductName'] = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
If $_POST['ProductName']['ProductName'] exists more than once how can I create a foreach loop based on that?
What I have tried so far...
foreach($_POST['ProductName']['ProductName']) {
}
This did not work...
What have I done wrong?
Complete Code:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
array_push($_POST["ProductName"], $stmt->fetch(PDO::FETCH_ASSOC));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['ProductName']['ProductName'];
// echo $_POST['ProductName']['Quantity'];
try {
$stmt1 = $conn->prepare("SELECT Stock FROM products WHERE ProductName = :ProductName");
$stmt1->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt1->execute();
$_POST['Stock'] = $stmt1->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['Stock']['Stock'];
$_POST['DEDUCT'] = $_POST['Stock']['Stock'] - $_POST['ProductName']['Quantity'];
try {
$stmt2 = $conn->prepare("UPDATE products SET Stock = :Stock WHERE ProductName = :ProductName");
$stmt2->bindParam(':Stock', $_POST['DEDUCT']);
$stmt2->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt2->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You can make a new array called (for example, $rows) which contains all of the fetched data using the function fetchAll() (fetch() only retrieves the next one row).
The most straightforward way to do this is as follows:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
//Add all returned values to an array called "$rows"
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then if you want to access that data later you can do:
foreach($rows as $row){
var_dump($row); //Show the data in the row to double-check
}
You can create array using foreach like this :
$newval_arr = array();
foreach($_POST['ProductName']['ProductName'] as $key=>$value) {
if(!in_array($value,$newval_arr) || empty($newval_arr))
{
$newval_arr[] = $value;
}
}
Then after you can use $newval_arr in foreach
foreach($newval_arr as $key=>$value)
{
//Your code herer
}

How to get the where clause with a bind variable to work in php

function get_grade($sku) {
require("config.php");
try {
$results = $db -> query prepare ("SELECT name, subject1,grade1,attendance,gender,subject2,grade2,subject3,grade3 FROM student WHERE sku = ?"); //binds the sku to the question mark
$results -> bindParam;
$results -> execute();
}
catch exception ($e) {
echo "could not connect";
exit;
}
$product = $results-> fetch (PDO::FETCH_ASOC);
}
How to get a where clause to work, where if the user has the same or similar attendance, subjects and grades then they will get then they will get that grade from a past student.
You need to bind $sku:
$results->bindParam(1, $sku);
This should work for you:
function get_grade($sku) {
require("config.php");
try {
$results = $db->prepare("SELECT name, subject1,grade1,attendance,gender,subject2,grade2,subject3,grade3 FROM student WHERE sku = :sku");
//^^^^^^^^Perpare statement here //^^^^Placeholder for variable
$results->execute(array("sku" => $sku));
//^^^^^^^^^^^^^^^^^^^Instead of binParam
} catch (PDOException $e) {
//^^^^^^^^^^^^^^^ Catch PDO exeption
echo $e->getMessage();
exit;
}
$product = $results->fetch(PDO::FETCH_ASOC);
}

php trying to return the number of rows in a sql table

Trying to return the total row count for a sql table. My code returns the number of rows that are added not the total number of rows in the table. Any suggestions?
PHP:
require(ROOT_PATH . "inc/database.php");
try {
$query = $db->prepare("REPLACE INTO launch_email VALUES ('$email')");
$query->execute();
$count = $query->rowCount();
echo $count;
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
rowCount() ist not a direct method of the PDO class, it is a method from PDOStatement.
Syntax:
public int PDOStatement::rowCount ( void )
Example based on your approach:
try {
$query = $db->prepare("REPLACE INTO launch_email VALUES ('$email')");
$query->execute();
$count = $query->rowCount();
} catch (Exception $e) {
...
PDO::exec returns the number of affected rows.
So you don't need to use rwoCount(), and note rowCount() is the method from PDOStatement.
require(ROOT_PATH . "inc/database.php");
try {
$count = $db->exec("REPLACE INTO launch_email VALUES ('$email')");
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}

how to return a value from a method inside another method php

i got two methods.one method is to insert data and the other one is to get the id of the inserted data. i tried several test but it doesn't give any return value.is it possible to pass a return value from another method?
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
//$log = $this->getSessionID($email);
return $this->getSessionID($email);
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
public function getSessionID($email) {
try {
//global $bcrypt;
$query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");
$query->bindValue(1, $email);
$query->execute();
$data1 = $query->fetch();
$id = $data1['id'];
//echo $id;
return $id;
} catch(PDOException $e) {
die($e->getMessage());
}
}
and the returning page is here:
if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
session_regenerate_id(true);
$_SESSION['id'] = $data;
//print_r($_SESSION);
header('location: registry.php');
exit();
}
Use the lastInsertID() method on your query object rather than a second query
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
$insertId = $query->lastInsertId(); // <!-- Use this instead of a second query
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
Its also important to note that you are not inserting the 'email address' into your database, so there is no way for the query to find it by that field if you were to use another SELECT statement. You might want to complete your INSERT statement.

Categories