This is my controller code which save data in table but when I put more than max length column data , it is not retuning me STATUS false; nothing is happening. please help
function saveImproveUs(){
$status =array("STATUS"=>"false");
try{
$improveUs = array(
'NAME' => trim($this->input->post('name')),
'EMAIL' => trim($this->input->post('email')),
'LOCATION' => trim($this->input->post('location')),
'MESSAGE_TYPE' => trim($this->input->post('messageType')),
'COMMENTS' => trim($this->input->post('comments'))
);
// Save improve us
$this->db->insert('trn_improve_us', $improveUs);
if ($this->db->affected_rows() > 0){
$status = array("STATUS"=>"true");
}
}catch(Exception $ex) {
//show_error($ex);
echo "I am in exception";
exit;
}
echo json_encode (array($status)) ;
}
You have to throw the exception, it won't do this for you.
if ($this->db->affected_rows() > 0){
$status = array("STATUS"=>"true");
}
else {
throw new Exception("Could not insert data");
}
Also inserting more data than a column can hold will automatically get cut-off in MySQL, the insert won't actually fail. You should use strlen to check the length of a string and validate it manually.
Related
I would like to find a way to check if my query result doesn't return a value. Example:
If in my tableExample on database there isn' t the id that I'm passing , the method should return an exception or a simple echo that indicate me the not presence in the table
My code below:
try{
DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
return $result= array("result" => "true" );
}catch(QueryException $e){
return $result= array("result" => "false" );
echo " - ".$e;
}
}
update method return integer value (affected rows) if success, try like this
try{
$update = DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
if($update){
$result = array("result" => true );
}else{
$result = array("result" => false,"message"=>"Not Found" );
}
}catch(QueryException $e){
$result = array("result" => false,"message"=>$e->getMessage() );
}
return $result;
Use findOrFail() helper method. That way you do not need to wrap the action in a try catch since if findOrFail does not find the row then it will throw an exception.
$resultData = DB::table('tableExample')->findOrFail(2);
$update = $resultData->update(['update' => "1"]);
if(!$update){
return response(['results'=>false]);
}
return response(['results'=> true]);
}
update() method returns a boolean true for success on update and versa.
You can do this by using the whereExists clause:
https://laravel.com/docs/5.5/queries#where-exists-clauses
https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html#method_exists
I'm trying to build a script where I need to read a txt file and execute some process with the lines on the file. For example, I need to check if the ID exists, if the information has updated, if yes, then update the current table, if no, then insert a new row on another temporary table to be manually checked later.
These files may contain more than 20,30 thousand lines.
When I just read the file and print some dummie content from the lines, it takes up to 40-50ms. However, when I need to connect to the database to do all those verifications, it stops before the end due to the timeout.
This is what I'm doing so far:
$handle = fopen($path, "r") or die("Couldn't get handle");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$segment = explode('|', $buffer);
if ( strlen($segment[0]) > 6 ) {
$param = [':code' => intval($segment[0])];
$codeObj = Sql::exec("SELECT value FROM product WHERE code = :code", $param);
if ( !$codeObj ) {
$param = [
':code' => $segment[0],
':name' => $segment[1],
':value' => $segment[2],
];
Sql::exec("INSERT INTO product_tmp (code, name, value) VALUES (:code, :name, :value)", $param);
} else {
if ( $codeObj->value !== $segment[2] ) {
$param = [
':code' => $segment[0],
':value' => $segment[2],
];
Sql::exec("UPDATE product SET value = :value WHERE code = :code", $param);
}
}
}
}
fclose($handle);
}
And this is my Sql Class to connect with PDO and execute the query:
public static function exec($sql, $param = null) {
try {
$conn = new PDO('mysql:charset=utf8mb4;host= '....'); // I've just deleted the information to connect to the database (password, user, etc.)
$q = $conn->prepare($sql);
if ( isset($param) ) {
foreach ($param as $key => $value) {
$$key = $value;
$q->bindParam($key, $$key);
}
}
$q->execute();
$response = $q->fetchAll();
if ( count($response) ) return $response;
return false;
} catch(PDOException $e) {
return 'ERROR: ' . $e->getMessage();
}
}
As you can see, each query I do through Sql::exec(), is openning a new connection. I don't know if this may be the cause of such a delay on the process, because when I don't do any Sql query, the script run within ms.
Or what other part of the code may be causing this problem?
First of all, make your function like this,
to avoid multiple connects and also o get rid of useless code.
public static function getPDO() {
if (!static::$conn) {
static::$conn = new PDO('mysql:charset=utf8mb4;host= ....');
}
return static::$conn;
}
public static function exec($sql, $param = null) {
$q = static::getPDO()->prepare($sql);
$q->execute($param);
return $q;
}
then create unique index for the code field
then use a single INSERT ... ON DUPLICATE KEY UPDATE query instead of your thrree queries
you may also want to wrap your inserts in a transaction, it may speed up the inserts up to 70 times.
I don't know why but the insert query fail, this is my code:
public function insert_resource($resource)
{
try
{
$data = array(
'descrizione' => $resource['descrizione'],
'sigla' => $resource['sigla'],
'colore' => $resource['colore'],
'planning' => $resource['planning'],
'data' => 0
);
if(!$this->db->insert('risorse', $data))
{
throw new Exception("Can't insert the resource");
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
Now the $resource contains all data like:
descrizione
sigla
colore
planning
data
except for the id, that's auto_increment so I doesn't include the id in the $data variable.
In the network tab I get:
Can't insert the resource
id: null
status: "SUCCESS"
why happean this?
LAST_QUERY
INSERT INTO `risorse` (`descrizione`, `sigla`, `colore`, `planning`, `data`, `id`) VALUES ('sdfdf', 'fdfd', '12FFEF', 'NoviSoft', 0, 'null')
$this->db->insert('risorse', $data);
if ( $this->db->affected_rows() == 0 ){
echo $this->db->_error_message();
throw new Exception("Can't insert the resource");
}
One of my class files has been spitting out the "There is no active transaction" warning when creating some records. It is the only one doing it and I can't figure out why because all my queries are executing successfully.
My php_errors log has given me zero insight to the issue, nor have any of the other related questions provided any solutions.
try {
App::$DB->beginTransaction();
$rQuery = App::$DB->prepare("INSERT INTO `Cervidae` (`".implode('`, `',array_keys($aSQL)) ."`) VALUES (".implode(",",$aPlaceholders).")");
$rQuery->execute(array_values($aSQL));
$this->_Cervid_ID = App::$DB->lastInsertId();
if (is_array($aData["Treatments"])) {
foreach ($aData["Treatments"] as $sTreatmentName => $sTreatmentData) {
$oTreatmentToCervid = new TreatmentToCervid(array("Treatment_ID" => $sTreatmentData["Treatment_ID"], "Cervid_ID" => $this->_Cervid_ID, "CreatedBy" => $aSQL["CreatedBy"], "UpdatedBy" => $aSQL["UpdatedBy"], "Dose" => $sTreatmentData["TreatmentDose"]), "NEW");
}
}
$oHerdSize = App::getFlat(self::get(array("COUNT(Cervidae.Cervid_ID) AS HerdSize"),array("Cervidae.Herd_ID = $nHerdID","Cervidae.IsActive = 1")));
$rQuery = App::$DB->prepare("UPDATE `Herds` SET `HerdSize` = ".$oHerdSize->HerdSize." WHERE `Herd_ID` = ".$nHerdID);
$rQuery->execute();
App::$DB->commit();
$this->__construct($this->_Cervid_ID, 'ID');
}
catch (Exception $e) {
App::$DB->rollBack();
throw new Exception($e->getMessage());
}
I have data (exact) from this HTTP POST:
rowno=1.00000000&date_line=2014-10-07&name=Dan%20Volunteer&affiliation=Enterprise&checkno=1701&amount=20025.00000000&total=20250.00000000¬es=&date_deposit=&rowno=2.00000000&date_line=2014-10-07&name=Harper%20Lee&affiliation=Enterprise%20B&checkno=1702&amount=225
then this code to process
<?php
file_get_contents("php://input");
$db = null;
if (isset($_SERVER['SERVER_SOFTWARE']) &&
strpos($_SERVER['SERVER_SOFTWARE'],'Google App Engine') !== false) {
// Connect from App Engine.
try{
$db = new pdo('mysql:unix_socket=/cloudsql/wonder:bread;dbname=loaf', 'root', '');
}catch(PDOException $ex){
die(json_encode(
array('outcome' => false, 'message' => 'Unable to connect.')
)
);
}
};
try {
if (array_key_exists('name', $_POST)) {
$stmt = $db->prepare('INSERT INTO entries (name, affiliation) VALUES (:name, :affiliation)');
$stmt->execute(array(':name' => htmlspecialchars($_POST['name']), ':affiliation' => htmlspecialchars($_POST['affiliation'])));
$affected_rows = $stmt->rowCount();
// Log $affected_rows.
}
} catch (PDOException $ex) {
// Log error.
}
$db = null;
?>
<?php
header("Content-type: application/vnd.fdf");
// read and store the data however you want
// reply with some FDF data
echo <<<RESPONSE
%FDF-1.2
1 0 obj
<< /FDF <<
/Status (Wham bam! File sent.)
>>
>>
endobj
trailer
<< /Root 1 0 R >>
%%EOF
RESPONSE;
?>
This http post has two records (row/recount count always varies), but only data from the last row is being inserted. Need all rows.
I'm going to stab at this one....I think what is happening is that you are just processing the return post as is, so the first rowno is being skipped over (rather the second rowno is overwriting the first). If you receive that post back as a string, you need to split it by preg_match() or explode() so that you can loop over it with your try.
Try this class on your string. This class will split the string into arrays based on rows. Then you need to take the resulting array $insert then process each array in your an sql loop...does that make sense?
class ProcessPost
{
public static function Split($value = '',$splitVal = 'rowno=')
{
if(!empty($value)) {
// Explode by row values
$rows = explode($splitVal,$value);
$rows = array_filter($rows);
if(is_array($rows) && !empty($rows)) {
foreach($rows as $_row => $querystring) {
parse_str($splitVal.$querystring,$_array[]);
}
foreach($_array as $row_key => $row_val) {
if(empty($row_val))
unset($_array[$row_key]);
}
return $_array;
}
}
}
}
$test = 'rowno=1.00000000&date_line=2014-10-07&name=Dan%20Volunteer&affiliation=Enterprise&checkno=1701&amount=20025.00000000&total=20250.00000000¬es=&date_deposit=&rowno=2.00000000&date_line=2014-10-07&name=Harper%20Lee&affiliation=Enterprise%20B&checkno=1702&amount=225';
$insert = ProcessPost::Split($test);