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.
Related
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 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
This code works and enters all of the correct information into the database but the error check returns an error. I could remove the error check but I'm afraid of creating some nightmare that comes back to haunt me later or that I'm missing a fundamental issue:
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
$categoryresult = mysql_fetch_array($sql5a);
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT INTO lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql5b) ) {
echo('sql5b updated successfully<br>');
} else {
echo('Error: sql5b not updated<br>'.mysql_error() );
}
if ( #mysql_query($sql6b) ) {
echo('sql6b updated successfully<br>');
} else {
echo('Error: sql6b not updated<br>'.mysql_error() );
}
The output is: "Error: sql5b not updated
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 'Resource id #7' at line 1"
"sql6b updated successfully"
When I check the database all entries are correct. If sql5a didn't work, sql6b couldn't work, hence my confusion over the error.
A sample Category would be: Travel/Leisure
The category was originally created from a form response:
$category = htmlentities($fbdetail['category'], ENT_QUOTES);
and entered into the database successfully. An id number was assigned using AUTO_INCREMENT.
You assign query to variable $sql5a, but call #mysql_query($sql5b).
$sql5b doesn't exist (at least in this sample). Same with $sql6a...
You can use INSERT syntax without VALUES, but you need to ommit INTO keyword.
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
if ( $res5a = #mysql_query($sql5a) ) { // first execute query and store resource in variable
echo('sql5a selected successfully<br>');
} else {
echo('Error: sql5a failed<br>'.mysql_error() );
}
$categoryresult = mysql_fetch_array($res5a); // fetch array passing the RESOURCE var, NOT query string
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql6a) ) {
echo('sql6a inserted successfully<br>');
} else {
echo('Error: sql6a failed<br>'.mysql_error() );
}
I don't know where you get $fbid2 or $category from, since it's not in this piece of code.
The syntax for the insert is :
INSERT INTO table(col1, col2 ...) VALUES(val1, val2 ...)
In your specific case:
$sql6a = "INSERT INTO table(fbid, categoryid) VALUES('{$fbid2}','{$oldcategoryid}')"
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}
I am completely stumped. Here is my php (CodeIgniter) code:
function mod()
{
$uid = $this->session->userdata('uid');
$pid = $this->input->post('pid');
if ($this->_verify($uid,$pid))
{
$name = $this->input->post('name');
$price = $this->input->post('price');
$curr = $this->input->post('curr');
$url = $this->input->post('url');
$query = $this->db->query("UPDATE items SET
name=".$this->db->escape($name).",
price=".$this->db->escape($price).",
currency=".$this->db->escape($curr),",
url=".$this->db->escape($url)."
WHERE pid=".$this->db->escape($pid)." LIMIT 1");
}
header('location: '.$this->session->userdata('current'));
}
The purpose of this code is to modify the properties (name, price, currency, url) of a row in the 'items' table (priary key is pid). However, for some reason, allowing this function to run once modifies the name, price, currency and url of ALL entries in the table, regardless of their pid and of the LIMIT 1 thing I tacked on the end of the query. It's as if the last line of the query is being completely ignored.
As if this wasn't strange enough, I replaced "$query = $this->db->query(" with an "echo" to see the SQL query being run, and it outputs a query much like I would expect:
UPDATE items
SET name = 'newname',
price = 'newprice',
currency = 'newcurrency',
url = 'newurl'
WHERE pid = '10'
LIMIT 1
Copy-pasting this into a MySQL window acts exactly as I want: it modifies the row with the selected pid.
What is going on here???
Now I feel stupid: all it took was seeing my code in a different font. My code has
currency=".$this->db->escape($curr),",
instead of
currency=".$this->db->escape($curr).",
The echoing made it work just fine because apparently you can give echo more than one string, comma separated, and it concatenates them
cries I spent hours on this
I know you answered your own question, but let me just add this to the pile: You're not leveraging CodeIgniter AT ALL in this sort of query - which if you used CI as it's intended, you wouldn't have had that typo. Your query should look like this (among other things):
$query = $this->db->update('items',
array('name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'curr' => $this->input->post('curr')),
array('id' => $this->input->post('id')),
1);
By assembling the query string by hand, you're undoing what CI does for you. Only when you're using some complex JOIN statement should you be writing your own SQL in CI, and even then, you want to use the sprintf PHP function to make sure you're not introducing typos.