INSERT INTO sqlsrv_query not working - sqlsrv

I'm trying to add records to a table with no success :( and even if the record is not added to the DB, it returns no error... I get "Ok" returned...
I know my connection is working cause when I change my query to FETCH info from that same table, it works.
public static function Test($pConn,$pNumEmploye,$pPrenom)
{
$query = "INSERT INTO [Test] ([NumEmploye],[Prenom]) VALUES(?,?)";
$params = array('12','test');
if(!sqlsrv_query($pConn,$query,$params))
{die( print_r( sqlsrv_errors(), true));}
else {return "ok";}
}
Please help before I go insane :)

Your code check doesn't check to see if the record has actually be imported into the database, that will only check if there is any errors, in your case there isn't any errors, so it will return false, and hence ok.
if(!sqlsrv_query($pConn,$query,$params))
{die( print_r( sqlsrv_errors(), true));}
else {return "ok";}
Meaning you need to use something else, such as sqlsrv_fetch function, in your case sqlsrv_rows_affected will probably work.

Related

Neo4j throwing Neo.ClientError.Transaction.TransactionHookFailed when Cypher is executed

Please can you please point what's wrong with this cypher statement because when the statement is executed, the database is throwing TransactionHookFailed error. Also, it might help if you can explain the meaning of this error.
MATCH (user:User { id: $userId })
MATCH (event:Event { id: $eventId })-[:BOUND_TO_EXPIRE]->(expiryDate)
WITH user, event, apoc.nodes.connected(user, event, 'ORGANIZED>') AS isOrganizer, expiryDate
// Make sure the user is the organizer of the event
WHERE isOrganizer = true
// Just delete event
DETACH DELETE expiryDate
DETACH DELETE event
// Remove event from the user's event
SET user.noOfEvents = user.noOfEvents - 1
RETURN {
clientResponse: true
}
I had this error
Neo.ClientError.Transaction.TransactionHookFailed
because a constraint on the database required certain fields to be set when updating a node. I was setting other fields but not the required ones.
Perhaps your database has constraints on it as well.
You would get a syntax error if the cypher code was bad, so that's probably not the case.

Cakephp : add condition in this->Model->save()

i am working on a cakephp 2.x .want to add a condition into my save query .. for example i want to implement this query
INSERT INTO 'this' where condition is 'this'
right now i am doing this
$count = $this->Message->find('count', array(
'conditions' => array('Message.mobileNo' => $mobileNo,
'Message.body'=>$body
)));
if($count>0){
echo "already have a message";
}else
{
$this->Message->create();
$this->Message->save($this->request->data);
}
at times now i am first checking through count and then saving into the database ... can i add condition into my save so i dont have to query two times into database just to accomplish one task
This is not really CakePHP question rather than MySQL. But you can't do this since the INSERT query doesn't have conditional query.
There are 2 ways of doing it:
As Mark in the comment said use validation. The validation although apply to single field, so it will be quite tricky to do it.
Use beforeValidate() or beforeSave() callbacks in your model to check this and if they return false the save operation wont be executed.
You can put UNIQUE index to your table so it won't allow insertion of phone+message together.
I would go with the method 2.
try the beforeSave methode in your Model
You can use the following code in a better way:
$conditions = array('Message.mobileNo' => $mobileNo,
'Message.body'=>$body);
if ($this->Message->hasAny($conditions)){
echo "already have a message";
}
else{
$this->Message->create();
$this->Message->save($this->request->data);
}

Codeigniter Extracting Information, Function Isn't Working

I'm attempting to extract information from my mysql database. I believe I'm properly joining tables (function syntax below) but when I try and display the extracted information inside of a view, nothing is showing up. I used var_dump and my array is saying
array (size=0) empty
I'm also getting these error messages as well.
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 6
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 7
My question is, where do you think I'm going wrong. What are some steps I should take to go about fixing my issue? (syntax below) Thanks Everyone.
My Model_data function
function getJoinInformation($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
My Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
My View
<?php
var_dump($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo $allvehicledata->make. ' ' .$allvehicledata->model . "<br />";
$make = $allvehicledata[0]->make;
echo "$make";
// $state = $cities[0]->state;
// echo '<hr>';
foreach ($allvehicledata as $car)
{
echo anchor('site/getAllInformation/'.$car->year.'/'.$car->make.'/'.$car->model, $car->year.' '.$car->make.' '.$car->model, array('title'=>$car->make.' '.$car->model)).'<br>';
}
}
?>
Your notice errors are happening because you are returning an array from your model function, yet are calling the data like it is an object. If you only want to retrieve one row of data from the DB, use row() instead of result(). Read Generating Query Results for more info.
The query you're running is not failing, but it is not returning any results. Chances are your WHERE conditions are not being given the values that you assume they are (that's my guess, anyway).
Use echo $this->db->last_query() after you perform the DB query to see exactly what SQL is being sent, and use that to figure out what may be wrong and why the result set is empty.

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

save() returning false, but with no error in CakePHP

My debug value is set to 2, and it's displaying all the queries, except the one I need.
I have an Items controller method that is calling this method in the User model (Item belongsTo User):
function add_basic($email, $password) {
$this->create();
$this->set(array(
'email' => $email,
'password' => $password
));
if($this->save()) {
return $this->id;
}
else {
return false;
}
}
I have confirmed that $email and $password are being passed into the function correctly (and are populated with legit data). email and password are the names of the fields in the User model.
I have also confirmed that on $this->save() it is returning false, but when I view the page where this occurs, the query is not being printed in the debug, and there is no error being thrown, so I have no idea whats going wrong.
Any ideas on how I can see the error, or why the query doesn't seem to be getting executed?
It's weird, cause right after this, I have another model saving data to it in the exact same fashion, it goes off without a hitch.
This will probably give you the info you need (assuming it's not saving because of invalid data, of course):
if(!$this->save()){
debug($this->validationErrors); die();
}
Have you got a beforeValidate() or beforeSave() method in the model or app model? Ifso, are they returning true? Failing that, use a debugger, set a break point in your IDE at the top of cake/libs/models/model.php save() method and step through the code until it returns false. Failing that add die('here'); calls.
Try this:
if ($this->save()) {
return $this->id;
}
else {
var_dump($this->invalidFields());
return false;
}
#cakePHP 3.6 and above: By default, the request data will be validated before it is converted into entities. If any validation rules fail, the returned entity will contain errors. It can be read by getErrors() method.
The fields with errors will not be present in the returned entity:
Say, you have an entity
use App\Model\Entity\Article;
$entity = $this->ModelName->newEntity([
'id' => 1,
'title' => 'New Article',
'created' => new DateTime('now')
]);
$result = $this->ModelName->save($entity);
\Cake\Log\Log::debug($entity->getErrors());
If you’d like to disable validation when converting request data, set the validate option to false:
$article = $articles->newEntity(
$this->request->getData(),
['validate' => false]
);
Ref: https://book.cakephp.org/3/en/orm/validation.html
Make sure to check your tables:
Does ID have auto increment enabled?
Is id your primary key?
the auto_increment issues killed me.
Easy way to check: if any of your rows have ID = 0, auto_increment is likely disabled.
CakePHP 3.6
$entity = $this->Model->newEntity([
'account_id' => $id,
'gallery_id' => $gallery_id
]);
$result = $this->Model->save($entity);
print_r($entity->getErrors());
The other situation where CakePHP fails to report any $this->Model->validationErrors and no other errors is potentially when $this->request->data isn't as Cake expects and is simply ignoring your data, not saving, no validation errors. For example if your data was provided by DataTables you might see this format $this->request->data[0]['Model']['some_field'].
$this->Model->save($this->request->data[0]) will work however.

Resources