I am trying to get the primary key by using SELECT LAST_INSERT_ID()but I am getting an error SQLSTATE[HY000]: General error
function logCallDetails($db,$student_id,$currentStory,$currentCall){
try{
$query= "INSERT INTO `call`(`student_id`, `story_id`, `call_number`) VALUES ('$student_id','$currentStory','$currentCall');SELECT LAST_INSERT_ID();";
echo $query;
$result=$db->prepare($query);
$result->execute();
$result = $result->fetchall(PDO::FETCH_ASSOC);
#$result->closeCursor();
return $result;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
initialize.php
$get_call_id=logCallDetails($db,$student_id,$call_number,$story_id);
foreach($get_call_id as $row=>$s)
{
foreach($s as $k=>$v)
{
echo $k.'->'.$v.'<br/>';
}
}
You've got 2 separate queries in a single query call. This is NOT allowed for security reasons by the underlying MySQL drivers. You'll have to prepare/execute the INSERT and SELECT queries separately.
function logCallDetails($db,$student_id,$currentStory,$currentCall){
$query= "INSERT INTO `call`(`student_id`, `story_id`, `call_number`)
VALUES (?,?,?)";
$result=$db->prepare($query);
$result->execute(array_slice(func_get_args()));
return $db->lastInsertId();
}
$get_call_id = logCallDetails($db,$student_id,$call_number,$story_id);
echo $get_call_id;
Related
How do I get the prepared statement of the mysqli_stmt-object?
If there is an error while executing the mysql-statement I want to return the statement.
$id = "89c483c8";
$query = "SELECT * FROM database WHERE id = ?";
if (!($stmt = $database->prepare($query) { ... }
else {
$stmt->bind_param("s", $id);
if (!$stmt->execute())
return $stmt->get_statement; //doesn't exist
}
"$stmt->get_statement" of course doesn't work. So how do I get the full query? In this example:
"SELECT * FROM database WHERE id = 89c483c8"
This is the best way to catch sql errors :
try {
$res = $mysqli_instance->query($query);
}catch (mysqli_sql_exception $e) {
print "Error Code <br>".$e->getCode();
print "Error Message <br>".$e->getMessage();
print "Strack Trace <br>".nl2br($e->getTraceAsString());
}
Or the simplest way :
echo $stmt->error
http://php.net/manual/en/mysqli.error.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.
try {$db=mysqli_connect( etc )
catch {
retry on time out
handle errors
}
try { if (!($errors = $db->prepare("insert into errors (`insert`,`error`) values(?,?);
print "\n*********prepare Error:" . $db->error;
}
}
catch { repeat above}
try {$errors->bind_param("ss",$sqlLoad,$errormsg); }
catch {repeat above)
....
try {$error->execute()} catch {repeat above error handling}
Now repeat all of that 10-40 times for different SQL queries on different fields.
That is a lot of duplicated code. Make my code hard to read, and if someone wants to add more sql queries they are forced to reduplicate large blocks of code.
I was thinking something like this but ran into a stumbling block with bind.
$sql[0]=array("name","select ? from <tablename>","s");
$sql[1]=array("name","select ?,? from <tablename>","ss");
$sql[2]=array("name","select ?,?,? from <tablename>","sss");
$sql[3]=array("name","select ?,?,?,? from <tablename>","ssss");
for(i=0;i<=3,i++){
try (
$preQuery[$sql[i][0]=$db->prepare($sql[i][1]);}
catch {}
try {$preQuery[$sql[i][0]]->bind_param($sql[i][2],????);} //Here is the trouble how do I define unique variables
catch { }
}
Here is some real code
It is a work in progress
foreach ($fieldspath as $field)
{
$filepath=$_SERVER[$field];
$result=$queryfile->execute();
$getres = $queryfile->get_result();
$numRows = -1;
$numRows = $getres->num_rows;
if ($numRows <>0)
{
$qryField = $getres->fetch_assoc();
$_SERVER[$field]=$qryField["id"];
$fileCount=$qryField["count"];
$fileRating=$qryField["rating"];
mysqli_query($db, "update Files set count=count+1 where `id` ='" . $qryField["id"] . "';");
continue;
}
else
{
$output = $insertFile->execute();
$result = $queryip->execute();
$getres = $queryip->get_result();
$qryField = $getres->fetch_assoc();
$_SERVER[$field]=$qryField["id"];
}
}
Notice: How I can re-execute a query just by:
$result=$queryfile->execute();
The query doesn't have to be re-stated, nor do the parameters. Everything is automatic. The actual queries are all listed at the top of the program, and I never have to see them, or restate them ever again. Also I don't need to cram my parameters into array before I can use them.
<?php
$pipeName = '/var/run/mysql/mysql.sock';
$username = 'user';
$password = 'password';
$db = new PDO('mysql:unix_socket='.$pipeName.";dbname=dbase", $username, $password);
$sql["errors"]="insert into errors (`insert`,`error`) values(:insert,:error);";
$sql["events"]="insert into event (`message`) values(?);";
$sql["queryip"]="select id,count,rating FROM ip where address=? limit 1;";
$sql["queryUsrAgent"]="select id,count,rating FROM http_user_agent where agent=? limit 1;";
$sql["insUsrAgent"]="insert into http_user_agent (`agent`) values (?);";
$sql["insertIP"]="insert into ip (`address`) values (?);";
$sql["insertReqURI"]="insert into request (`REQUEST_URI`) values (?);";
$sql["queryReqURI"]="select * FROM request where REQUEST_URI=? LIMIT 1;";
$sql["queryfile"]="select id,count,rating FROM Files where path=? limit 1;";
$sql["insertFile"]="insert into Files (`path`) values (?);";
$sql["cntIp"]="update ip set count=count+1 where `address` = :ip";
$sql["cntFiles"]="update Files set count=count+1 where `id` = :id;";
$sql["cntAgent"]="update http_user_agent set count=count+1 where `agent` = :agent;";
$sql["reqRequest"]="select * FROM request where REQUEST_URI= :requesturi LIMIT 1;";
$sql["cntRequest"]="update request set count=count+1 where `REQUEST_URI` = :requesturi;";
$ready=doPrepare($db,$sql);
$ready["errors"]->execute(array("insert"=>"stuff","error" =>"stuff"));
pdoRun($ready,"errors",array("iniisert"=>"iiiii","error" =>"yyyyyggg"));
function doPrepare($db, $enmass) {
foreach ($enmass as $key => $sql) {
try {
$stmt[$key] = $db->prepare($sql);
} catch (PDOException $e) {
print "\nStuff";
trigger_error($e);
return false;
}
}
return $stmt;
}
function pdoRun($ready,$query,$vals) {
try {
$ready[$query]->execute($vals);
} catch (PDOException $e) {
print "\nExecution fail";
}
}
// $stmt->execute(array_values($column_values));
?>
Making prepared queries like you are doing doesn't work like you seem to think it does. The parameter placeholders can only substitute for literal values. You can't use them for column names or table names or anything else.
You also can't prepare a query like "select ? from" because it names no table. It's not a syntactically complete query.
The better practice is to code a "helper function" that does the prepare and execute for you. You can reduce repetitive code that way.
By the way, I find PDO is much easier than Mysqli when coding a helper function like this, because you don't have to use the bind_param() with variable arguments. In PDO, you just pass an array of arguments to execute().
function doInsert($db, $sql, $params) {
try {
$stmt = $db->prepare($sql);
$stmt->execute($params);
} catch (PDOException $e) {
trigger_error($e);
return false;
}
return true;
}
Now call it this way:
$sql = "insert into errors (`insert`, `error`) values(?, ?)";
$success = doInsert($db, $sql, [$sqlLoad, $errormsg]);
You might even like the function to format your INSERT statement for you:
function doInsert($db, $table, $column_values) {
$placeholders = array_fill(1, count($column_values), '?');
$columns = implode(',', array_keys($column_values));
$sql = "INSERT INTO `$table` ($columns) VALUES ($placeholders)";
try {
$stmt = $db->prepare($sql);
$stmt->execute(array_values($column_values));
} catch (PDOException $e) {
trigger_error($e);
return false;
}
return true;
}
Then call it like this:
$success = doInsert($db, "errors", ["insert"=>$sqlLoad, "error"=>$errormsg]);
You'll have to do something to apply back-ticks to the column names too.
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");
}
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;
}