I'm running a codeigniter application, and i can't get this simple insert to work well.
if(!$this->db->insert('myTable',$entry)){
$p3 = 0;
}else{
echo $this->db->last_query();
var_dump($this->db->_error_message());
}
the debug in the "else" clause always show me an empty string for error message, and if i test the last_query in phpmyadmin, the insert work well.
But the insert isn't happening when i normally run the app, even if the "else" is launched, implying the request succeed.
any clue ?
UPDATE : exemple of $entry array :
$entry = array(
'id' => '',
'id_devis' => $current[0]->id,
'metier' => $_POST[$i+1 . '_create_metier'],
'days' => $_POST[$i+1 . '_create_daycount'],
'price' => $_POST[$i+1 . '_create_price'],
'cr_date' => date('Y-m-d H:i:s'),
'user' => ''
);
$current is an extract of another table (using $this->db->get), and all the datas are fine, since i can insert them through the echo of last_query()
Put
error_reporting(E_ALL);
ini_set('display_errors', '1');
before the line with the insert. You should see an error message.
My guess is that you try to insert an illegal value for id. Possible reasons:
- It should not be empty.
- It can not be a string (ie. if the type is an integer)
Most of the time an id in the database is of type int and is an auto-increment field. If so, you should not try to insert an id. It will be created for you.
Just found out the issue, there wasn't. a script was deleting the line i just inserted further in the code, the insert was successful. Thanks for your answers all
Related
I working in a php application where I must delete the selected items from a list where each item haves their own ID from mysql database, everything goes ok until execute the query in php.
This is the error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
this is the String that I execute in the query:
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda in ($deletar);"
The variable $deletar receives their value from post method and their value is like: 35,36,47,... and can be one ore many different values
But my problem is if I change $deletar for the exactly values everything goes fine, but if I use the php variable with THE EXACTLY SAME VALUE it doesn't work and returns the previous error message, I have no more ideas about what to do... I wanna keep in this way where I can choose all IDs that I want delete, without repeat the query.
Thanks.
edit:
foreach($deletar as $val)
{
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda = $val;"
}
your code is not working because $deleter is return multiple value.
check code it's working.
Why don't you use a safe parametrized query?
$db =new PDO('... your connection string ... ');
$stmt = $db->prepare("delete from md5_agenda
where id_empresa = :empi
and id_unidade = :unii
and id_usuario = :usrr
and id_item_agenda in (:deletar);");
$stmt->execute(array(
':empi' => $empi,
':unii' => $unii,
':usrr' => $usrr,
':deletar' => $deletar
)
);
I have answers table with fields id player_id read_status
I am trying to update read_status:
$this->Answer->updateAll(
array(
'Answer.' . "'" . $data['field'] . "'" => "'" . trim(base64_decode($data['option'])) . "'"
),
array(
'Answer.id' => trim(base64_decode($data['id']))
)
);
The following fields are dynamic and coming from AJAX Request:
$data['field'] contains read_status
$data['option'] contains base64 encoded yes
$data['id'] contains base64 encoded id
The error I am getting is:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Answer.'read_status'' in 'field list'
SQL Query:
UPDATE
`skii`.`answers` AS `Answer`
LEFT JOIN
`skii`.`players` AS `Player` ON (`Answer`.`player_id` = `Player`.`id`)
SET
`Answer`.`'read_status'` = 'yes'
WHERE
`Answer`.`id` = 2
Notice: If you want to customize this error message, create app\View\Errors\pdo_error.ctp
Don't do that
The conditions you're generating are:
WHERE
`Answer`.`id` = 2
There is no reason to use updateAll for that, the primary use cases for updateAll are:
Updating multiple records
Updates by not-primary-key
Updates such as incrementing a counter atomically
Call save
Instead, just call saveField:
$this->Answer->id = $id;
$this->Answer->saveField($field, $val);
or save:
$this->Answer->id = $id;
$this->Answer->save(array($field => $val));
Validate your inputs
If you choose to continue using the code in the question know that it is dangerous.
Feeding user input directly to updateAll allows for the possibility to inject arbitrary SQL. Ensure the data is the data you expect:
With the updateAll call there's nothing to prevents someone submitting as $field:
"read_status = 'yes' AND correct ="
achieving this sql:
SET `Answer`.`read_status` = 'yes' AND correct = 'yes'
It is generally a bad idea to ever put user input in the key of a CakePHP model array (update, conditions, order) as the key is not expected to be potentially malicious by CakePHP and therefore not subject to the same escaping logic applied to values.
Therefore, escape all user input:
$ds = $this->Answer->getDatsource();
$id = (int)trim(base64_decode($data['id']));
$field = $this->Answer->escapeField((base64_decode($data['field']));
$val = $ds->value(trim(base64_decode($data['option']))), $field);
With the above logic and attempting the same injection as shown in the first example the result would be:
SET `Answer`.``read_status` = 'yes' AND correct =` = 'yes';
Which would simply fail rather than permit users to arbitrarily manipulate the database.
Note that the base64 encoding, if it's been added as a "security" measure, does nothing.
It seems the proble is that you are escaping the field name with single quotes:
`Answer`.`'read_status'` = 'yes'
should be
`Answer`.`read_status` = 'yes'
The following change should fix that:
$this->Answer->updateAll(
array('Answer.' . $data['field'] => trim(base64_decode($data['option']))),
array('Answer.id' => trim(base64_decode($data['id'])))
);
Try this :-
$this->Answer->updateAll(
array(
'Answer.' . $data['field'] => "'" . trim(base64_decode($data['option'])) . "'"
),
array(
'Answer.id' => trim(base64_decode($data['id']))
)
);
Got the lower portion here sorted, but now there's an issue when it inserts the record. I have the NULL value for file formatted as %s for string, but it's not inserting NULL it's inserting [BLOB - 0B]. The column format in the mySQL table is longblob. Any ideas?
this is my first time using $wpdb->insert and it looks like I've missed something.
Here's the loop I'm trying to use. There are currently 2 timestamps in the array.
for ( $i = 0; $i < count($timestamps); $i++ ) {
$working_time = $timestamps[$i];
$working_form = $formnames[$i];
$status_data = array(
'submit_time' => $working_time,
'form_name' => $working_form,
'field_name' => 'lead_status',
'field_value' => 'new',
'field_order' => 10001,
'file' => NULL
);
$status_data_types = array(
'%f',
'%s',
'%s',
'%s',
'%d',
'%s'
);
$result = $wpdb->get_results("SELECT field_value FROM ".$leadtable." WHERE submit_time = ".$working_time);
if(!$result) {
$insert = $wpdb->insert($leadtable, $status_data, $status_data_types);
if( !$insert ) {
echo 'didn\'t work';
}
}
}
I know that $working_time and $working_form are both set properly. $working_time is a long float like 1387175380.9600 and $working_form is a string.
Nothing is being returned, even by the if( !$insert ) check so I'm guessing it's erring somewhere before that point. I know that if( !$result ) will return true because that data does not exist yet.
Found the issue. The get_results query was failing due to a missed period. My HS English teacher was right... a missed period can be a HUGE problem!
If you want to get the last error and last query you can use this properties of $wpdb object:
$wpdb->last_error
will show you the last error, if you got one.
$wpdb->last_query
will assist you with showing the last query (where the error occurred)
I hope this will help you out.
Maybe your config hides error showing. Have you tried $wpdb->print_error();?
https://core.trac.wordpress.org/ticket/32315
One of the columns inputs may be larger than the column is.
Wordpress detects this and will not even send the query to the DB.
The Diff there shows a patch for wp-db you can put in to get more information in the last_error message so it will not be empty.
Hopefully, you have defined the global variable $wpdb.
If your $wpdb is not working, and also not showing any error then you must try these three steps.
Print your error using with errors functions.
echo $wpdb->last_error;
or
echo $wpdb->show_errors;
If no error is visible then you must print your last query using with last query function.
echo $wpdb->last_query;
Copy and paste your last query in your Phpmyadmin > Your Database -> Table -> SQL tab, click on the Go button, and you will definitely get proper solutions(errors) in it.
I have an insert process. My development is under Drupal6. So i used the following method to insert into database table.
$sid = $user->sid;
$data = array(
'nid' => $parent_nid,
'vid' => $parent_vid,
'uid' => $user_id,
'time_start' => time(),
'session_id' => $sid
);
drupal_write_record('quiz_node_results', $data);
Here the problem is, it is not inserting the value $sid. It inserts the default value 0 always in that field. But other values are inserted correctly. But it has value. I checked with by putting print_r($data).
In database table, session_id field's datatype is varchar.
For quick fix, i wrote actual insert query and inserted into it. That query is below.
$sql = "INSERT INTO {quiz_node_results}(nid, vid, uid, time_start, session_id) VALUES(".$parent_nid.",".$parent_vid.",".$user_id.",".time().", '".$sid."')";
db_query($sql);
It is working fine and inserts the value correctly. But i don't want to insert in this way because it is vulnerable.
I want to know why the above one is not working. Can anyone suggest where i went wrong?
I'm pretty sure changing line 1 from this:
$sid = $user->sid;
to this:
$sid = isset($user->sid) ? $user->sid : session_id();
should do the trick...
I´m reading Kevin Yank´s book "PHP and MySQL Novice to Ninja 5th edition", and found an error there in the code, and would like someone to help me out with it, maybe is a silly typo...?
I´m trying to follow the author´s example of creating and accessing a database of jokes. I´m learning how to join two databases to show with php a list of all the jokes.
I have two databases joke and author.
I´ve got this:
try{
$sql = 'SELECT joke.id, joketext, jokedate, name, email
FROM joke INNER JOIN author
ON authorid = author.id';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error: ' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],
'date' => $row['jokedate'],
'name' => $row['name'],
'email' => $row['email']
);
}
include 'jokes.html.php';
Now, all was working ok, until I´ve replaced the simple code to select the database information from just one table, to the INNER JOIN code.
This is the book´s code, wich I´ve followed.
In the jokes.html.php file, I´ve got this (wich I think is what´s giving me the error):
foreach($jokes as $joke):
<form action="?deletejoke" method="post">
<?php
echo 'id. ';
echo htmlspecialchars($joke['id'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['date'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['name'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['email'], ENT_QUOTES, 'UTF-8');
?>
<input type="hidden" name="id" value="<?php echo $joke['id'];?>">
<input type="submit" value="Borrar">
?>
<br></form>
<?php endforeach; ?>
Now, the error that throws me is:
Notice: Undefined variable: jokes in C:\xampp\htdocs\workspace1\jokes.html.php on line 10
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\workspace1\jokes.html.php on line 10
Line 10 of jokes.html.php is:
foreach($jokes as $joke):
I´m trying to get more information about foreach() but I can´t spot the error...
If anyone could help me out a bit (or maybe a clue!) I would be very grateful.
Thanks!!!
Rosamunda
UPDATE:
As the result of the query (trying it directely from phpmyadmin) was zero, so there were no database results for that query. I´ve decided to manually add one result doing this:
INSERT INTO joke SET
joketext = 'this is a new joke....',
jokedate = '2012-01-01',
authorid = 1;
Now, the errors have dissapear, and that single results does show.
What I don´t understand is:
Why didn´t just no result showed up, instead of those errors?
How do you manage these situations? I mean, it can happen that a query just have no results at all, is it common to result in those errors?
One of your helpful comments says that $result is empty... so why when the query isn´t zero those errors won´t show up?
Thanks again for your help!!! Rosamunda
I´ve found the answer in a SitePoint forum (the Book´s forum), and I thought that it would be nice to post the question here, just in case anyone wonders, or just in case anyone out there happens to have the same problem.
It is because of your php settings to show Notices and Warnings. The
notice/warning is valid because you were attempting to use the $jokes
variable before you declared/assigned a value to it. You can solve
this by putting $jokes = array(); before PHP Code:
foreach ($result as $row)
{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],
'date' => $row['jokedate'],
'name' => $row['name'],
'email' => $row['email']
);
}
That will at least declare the $jokes variable for in the event that
there are zero results.
So, I think the conclusion (please correct me if I´m wrong here!) is that you should always declare any variable that you pretend to use, just in case it happens to have no results. Because if it is empty it will show a nasty error message that will freak you out.
And to declare a variable you use $variablename = array().