Thanks for reading.
Reading through all the articles on here helped me locate my problem, I'm just not sure how I should edit the code. I still learning.
The message I get is:
SELECT attachid
FROM ilace_attachment WHERE attachtype = 'ads' AND user_id ='6' AND ads_id='1'
MySQL Error : Unknown column 'ads_id' in 'where clause'
Error Number : 1054
This all started after I upgrade my software script to a newer version. I checked the ads_ads in MYSQL and there isn't a colum for ads_id, just one called; id.
I believe the solution to my problem is to change the "ads_id" to just "id". But I'm not sure if thats right or what I should change.
$sql = $ilace->db->query("SHOW TABLE STATUS LIKE '". DB_PREFIX ."ads_ads'");
$ads_id_temp = $ilace->db->fetch_array($sql);
$ads_id=$ads_id_temp['Auto_increment'];
}
else
{
$ads_id=$ilace->GPC['id'];
}
$attachid = $ilace->db->fetch_field(DB_PREFIX . "attachment", "attachtype = '".'ads'."' AND user_id ='".$_SESSION['ilacedata']['user']['userid']."' AND ads_id='".$ads_id."'", "attachid");
Here is the script it runs.
http//wwwWEBSITEcom/campaign.php?id=0&cmd=_create- campaign&1=Advertise+here+for+%245.00+per+1000+views&2=Targeted+AdTITLENAME+adverts&3=http%3A%2F%2FwwwWEBSITEcom%2Fcampaign.php%3Fcmd%3Dcreate%26mode%3Dppc&4=Vist&zone=header&mode=PPI&clicks=0&5=1&keywords=KEYWORD1%2C+was%2C+KEYWORD2%2C+KETWORD3%2C+KEYWORD4&dotw[1]=1&dotw[2]=1&dotw[3]=1&dotw[4]=1&dotw[5]=1&dotw[6]=1&dotw[0]=1
You change AND ads_id= to AND id= because that is the field name in the SQL statement, and seemingly the field name has changed.
You do not change $ads_id because that is the name of your PHP variable, and this works fine as it is and does not need to be the same as the field name.
On a wider level, you should sit and figure out how the last line of the PHP quoted puts together the SQL statement quoted in the error. You should know that the . is used to concatenate strings together, that PHP strings must start and end with the same character but that can be either ' or ", and that the SQL statement requires ' around values.
Also, if you've updated a third-party software script and it's now incompatible with your database you should look to see if there was some sort of data migration script that you've not run.
Depends. Is the id column containing the same information as ads_id? If so, yes you should change it. If no, you should figure out what happened to the ids and why they were removed.
Related
Answer found (syntax): The column name of my string had to be encased in backticks " ` " as they contained spaces. Note that this means that the majority of this post has no relevance to the issue. The code has been corrected in case someone wants to do something similar.
So, I am doing a foreach loop to assign a value (1/0) to non-static columns in my database (it needs to support addition/deletion/editing of columns). I am using $connectionvar->query($queryvar); to do my queries which worked fine up until now when I'm trying to use a custom built string as $queryvar in order to change the column name to a variable within the loop. I've been outputting this string through echo and it looks exactly like my functional queries but somehow doesn't run. I've attempted to use eval() to solve this but to no avail (I feel safe using eval() as the user input is radio buttons).
Here's the loop as well as my thought processes behind the code. If something seems incoherent or just plain stupid, refer to my username.
foreach($rdb as $x) { //$rdb is a variable retrieved from $_POST earlier in the code.
$pieces = explode("qqqppp", $x); //Splits the string in two (column name and value) (this is a workaround to radio buttons only sending 1 value)
$qualname = $pieces[0]; //Column name from exploded string
$qualbool = $pieces[1]; //desired row value from exploded string
$sql = 'UPDATE users SET '; //building the query string
$sql .= '`$qualname`';
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\''; //$profilename is retrieved earlier to keep track of the profile I am editing.
eval("\$sql = \"$sql\";"); //This fills out the variables in the above string.
$conn->query($sql); //Runs the query (works)
echo ' '.$sql.' <br>'; //echoes the query strings on my page, they have the exact same output format as my regular queries have.
}
}}
Here's an example of what the echo of the string looks like:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
For comparison, echoing a similar (working) query variable outside of this loop (for static columns) looks like this:
UPDATE users SET profiletext='qqq' WHERE username='Admin2'
As you can see the string format is definitely as planned, yet somehow doesn't execute. What am I doing wrong?
PS. Yes I did research this to death before posting it, as I have hundreds of other issues since I started web developing a month ago. Somehow this one has left me stumped though, perhaps due to it being a god awful hack that nobody would even consider in the first place.
You need to use backticks when referring to column names which have spaces in them. So your first query from the loop is outputting as this:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
But it should be this:
UPDATE users SET `Example Qualification 3`='1' WHERE username='Admin2'
Change your PHP code to this:
$sql = 'UPDATE users SET `'; // I added an opening backtick around the column name
$sql .= '$qualname`'; // I added a closing backtick around the column name
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\'';
Example Qualification 3 : Is that the name of your Mysql Column name ?
You shouldnt use spaces nor upper / lower case in your columnname.
Prefere : example_qualification_3
EDIT :
To get column name and Comment
SHOW FULL COLUMNS FROM users
I am trying to pull user data from a Cart66 table I have and put it into a shortcode in wordpress. $account is an integer pulled from session data. The code below returns nothing.
$account =Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
foreach ($fname AS $row)
{
echo $row;
}
This returns "Array"
return $fname;
Ok firstly, maybe I am the only one who saw this, and it could be the source of your entire problem, but you have a misplaced double quote, at the end of your SQL line, which should live at the end of the actual SQL string, not after the requested return type:
// at the end of this line you have: '$account', ARRAY_N");
// this should be changed to: '$account'", ARRAY_N);
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
Even the first person who answered the question did not correct you, so I am assuming he didn't see it either. Secondly, using single quotes (') to escape a table name is invalid. If it is quoted at all, use backticks (`). Single quotes indicate a string, not an database, table, or field, all three of which should only be quoted with backticks (except on utility queries like SHOW). Use this instead:
select * from `vfp_cart66_accounts` where id = '$account'
Thirdly, as your commenters point out, you could be vulnerable to SQL Injection. Make sure to use the tools that WP gives you, and do this, or similar, instead:
$fname = $wpdb->get_results(
$wpdb->prepare(
'select * from `vfp_cart66_accounts` where id = %d',
$account
),
ARRAY_N
);
Lastly, you are requesting an array from the DB, but you are trying to echo it as if it were a scalar value. This explains why printing the value of $row yields "Array". When you convert an array() to a string, by default, you get "Array", since arrays can be complex data that may not be beautifully converted to a string. As a correction of this, you can do one of two things.
First, if you need the entire resulting array that represents the entire row of the table, then you can simply change your echo code to this:
foreach ($fname as $row) {
// print the fname of the row
echo $row['fname'];
// do the other stuff you need to do with $row
...
}
OR, if you simply need the fname field out of that table, for the given id, you could use a different $wpdb function, called $wpdb->get_var(), which gets one specific field from the first entry of the resulting data from the database, coupled with some minor SQL changes:
// use the get_var() function instead
$fname = $wpdb->get_var(
$wpdb->prepare(
// 1) change the 'fields' of your sql to only get the `fname` field
// 2) also add limit 1, to reduce load by only asking for one row
// NOTE: #2 is optional really, because WP does this for you when using get_var,
// but is good practice to only ask for what you need. so do it
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname; // print the value of field fname from vfp_cart66_accounts for id $account
Now. I don't have specific knowledge of Cart66. That being said, if the above changes to PHP, WordPress, and SQL syntax do not yield results, then you are probably having one of the following other problems instead:
there is a different PHP error somewhere in the code, causing this to never run
this code is never called, and thus it is never executed
you misspelled the table name, which is causing an SQL error
the table exists, but does not have a field named id
both table and field exist, but there are no entries in the table
some other random thing that is not coming to mind
DEBUG #1
For #1, you could try turning on error_reporting() and display_errors early in the code execution. In a normal, run of the mill PHP script you could add the following two lines somewhere early in the code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
However, you are using WordPress, so you will need to do something like this in your wp-config.php file:
// find the line that looks like this and comment it out
// define('WP_DEBUG', false);
// add these two lines directly below it
define('WP_DEBUG', true);
ini_set('display_errors', 1);
DEBUG #2
Make sure your code is running. Don't be afraid to throw a die() statement directly above it, to make sure it is running. Something like this:
// add a die() before everything
die('I am running. Awesome!');
// revised code
$account = Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname;
DEBUG #3
To debug #3, you need either access to a commandline tool for MySQL or some type of GUI interface like phpMyAdmin, so that you can run a query directly from the database. Here is the query you should run:
show tables like 'vfp_cart66_%';
This is an example of one of the only places in SQL that you should ever quote a table name in single quotes. Running this will yield a list of all the tables that start with vfp_cart66_. If you get no results, then your table name is wrong. If your results do not include vfp_cart66_accounts, then your table name is wrong. If you see vfp_cart66_accounts, you are good to go.
DEBUG #4
This one will need to be run directly from the DB or through something like phpMyAdmin also. You are trying to make sure you have the correct field name. The way you do that is:
show create table `vfp_cart66_accounts`;
Assumedly, the field you are calling id would be the auto_incremented field in the table. Thus you are looking for a line, similar to this one:
`id` bigint(20) NOT NULL AUTO_INCREMENT,
Make sure that the line that has AUTO_INCREMENT on it, begins with:
`id`
If it does not, and the name is something else other than id, then you probably have the wrong field name.
DEBUG #5
Make sure you actually have data to display. From your mysql console or phpMyAdmin, run:
select * from `vfp_cart66_accounts` limit 1;
If you bet any results, then you have data, and you are good.
DEBUG #3 - #5 (alternate methods)
Another option you have is to dump the $wpdb object, directly after you run the query, because it contains the last error you received from MySQL. You can do this like so:
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
// dump a readable version of the $wpdb object
echo '<pre>';
print_r($wpdb);
die('</pre>');
Often times, reading the MySQL error message helps narrow down the problem in your SQL syntax.
DEBUG #6
If none of this has helped at all, then you will need to use your experience to trackdown a random bug in either your plugins or theme, what could literally be anything. You may as well not even dig in core WP code because, while it does have a couple minor bugs unrelated to your problem, which are getting repaired as we speak, it is one of the most stable CMS platforms out there. It is used by more of the top 10 million sites on the internet than any other CMS, for a good reason. It works, it is up-to-date, and most of all, it is stable.
I really hope you found this helpful or at least learned something from it. Hopefully others find it useful as well.
$fname=$wpdb->get_results(
"SELECT * FROM `vfp_cart66_accounts` WHERE id = '$account'",
ARRAY_N"
);
when i run my php page this error show:
Unable to run query:Unknown column 'NUM_OPTIONAL_COLLEGE_COURSE' in 'field list'
$sql ="INSERT INTO MAJOR (`COL_NO`, `DEPT_NO`, `YEAR`, `NUM_OPTIONAL_UNI_COURSE`,
`NUM_MANDATORY_UNI_COURSE`, `NUM_OPTIONAL_COLLEGE_COURSE`,
`NUM_MANDATORY_COLLEGE_COURSE`, `NUM_OPTIONAL_DEPT_COURSE`, `NUM_MANDATORY_DEPT_COURSE`,
`NUM_FREE_COURSE`, `NUM_CUSHIONS_COURSE`, `NUM_OF_CREDIT`)
VALUES('$myq1','$myq2','$myq3','$myq4','$myq5','$myq6','$myq7','$myq8','$myq9',
'$myq10','$myq11','$myq12')";
can you help me in this ?
There is no column named NUM_OPTIONAL_COLLEGE_COURSE in table MAJOR. Re-check your column name, most probably its a spelling mistake.
The Error says it all
Verify NUM_OPTIONAL_COLLEGE_COURSE is the column name in the schema
Most errors occur if you have a column like " NUM_OPTIONAL_COLLEGE_COURSE" (mind the space in front) - use your Database Management System and Copy the name of the column.
Its a database schema error, The error means the column does not exist in table. You have to check out it carefully....You should also check, may be you are connected with wrong database. Once I also faced this type error, and my idiocy , I was runing my query on wrong database.
I'm pretty new to web development so there's a good chance I'm doing something pretty dumb here.
I'm using AJAX to send data to a PHP file which will use the data to run SQL commands to update a table. I'm dealing with editing articles, so my PHP file needs to know three things: The original name of the article (for reference), the new name and the new content. I also tell it what page the user is looking at so it knows which table to edit.
$('#save_articles').click(function () {
var current_page = $('#current_location').html();
var array_details = {};
array_details['__current_page__'] = current_page;
$('#article_items .article_title').each(function(){
var article_name = $(this).html(); //The text in this div is the element name
var new_article_name = $(this).next('.article_content');
new_article_name = $(new_article_name).children('.article_content_title').html();
var new_article_content = $(this).next('.article_content');
new_article_content = $(new_article_content).children('.article_content_content').html();
array_new_deets = {new_name:new_article_name, content:new_article_content};
array_details[article_name] = array_new_deets;
});
send_ajax("includes/admin/admin_save_articles.php", array_details);
});
In the PHP file, I first retrieve the current page and store it in $sql_table and then remove the current page variable from $_POST. Then I run this.
foreach($_POST as $key => $value){
$original_name = $key;
$new_name = $value['new_name'];
$new_cont = $value['content'];
$query = "UPDATE
`$sql_table`
SET
`element_name`= '$new_name',
`element_content` = '$new_cont',
WHERE
`element_name` = '$original_name'";
$query = mysql_query($query);
if(!$query){
die(mysql_error());
}
}
I always receive an error saying that 'sitep_Home' is an incorrect table name. Not only is it a real table in my db, but I've actually changed its name to make sure it isn't an issue with keywords or something.
If I instead run the query without the variable $sql_table (specifying that the table is called 'sitep_Home'), the query accepts the table. It then doesn't actually update the table, and I suspect it's because of the WHERE argument that also uses a variable.
Can anyone see what I'm doing wrong here?
try to use $sql_table as '$sql_table' if you are sure that this contain a right table name.
Like you are using other column's value
Check if this can help!!
Dump/log your query before executing it - the problem should be quite visible after that (I suspect some additional characters in the table name).
Couple of things:
you should never trust your users and accept everything they'll send you in $_POST, use whitelist for the fields you'd like to update instead
your code is vulnerable to SQL injection, I recommend to use some framework / standalone library or PDO at least, avoid mysql_query which will be deprecated in the future. Check this to get some explanation http://www.phptherightway.com/#databases
Table names are case sensitive in MySQL. Please check if there is mistake in the case.
You have to surround name of mysql table in query in this `` qoutes. When you dinamically create mysql table it is very important to trim($variable of mysql name table) before create, because if "$variable of mysql name table" have space in the edns or in the start mysql not create table. And the last when you call dinamically $variable of mysql name table in query you have to trim($variable of mysql name table) again.
I am pulling back some data from the twitter query API, and parsing it through PHP like so:
$i =0;
foreach ($tweetArray->results as $tweet) {
$timeStamp = strtotime($tweet->created_at);
$tweetDateTime = date('m-d-Y H:m:s', $timeStamp);
if($i > 0){
$SQL .= ',';
}
$SQL .= "(". $tweet->id .",'" . $tweet->from_user ."','". addslashes($tweet->profile_image_url) . "','". addslashes($tweet->text). "','" . $tweetDateTime ."')";
$i++;
}
$SQL .= " ON DUPLICATE KEY UPDATE 1=1";
This leaves me with a SQL statement looking like this:
INSERT
INTO
tblTwitterSubmit (tweetId, twitterAuthor, authorAvatar, tweetText, tweetDateTime)
VALUES
(111,'name','http://url.com','a string of text','03-04-2011 13:03:09'),
(222,'anothername','http://url.com','another tweet','03-04-2011 12:03:51')
ON DUPLICATE KEY UPDATE 1=1;
I am unfortunately getting the following error: 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 '1=1' at line 1.
Edit:
The 1=1 is supposed to not do anything. The tweets don't change, and so if I pull the same one back twice for any reason, nothing will happen, but it also won't throw a duplicate key error.
Re-edit:
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just make a bunch of submissions instead of one long sql string.
Hopefully this is better practice.
Leaving this open for a couple minutes hoping for some feedback if this is the way to do it or not.
The ON DUPLICATE KEY UPDATE requires a column name, something like this, assuming tweetId is the key column that's getting duplicates.
ON DUPLICATE KEY UPDATE tweetId=tweetId+1
Your 1=1 doesn't actually do anything.
Are you sure you're using the right syntax for on duplicate key update ?
Judging from it's manual's page, it seems you have to specify a column name, and not 1=1.
From what I understand, if you want to indicate "use the value from the values() clause when there's a duplicate", you should use something like this :
on duplicate key update your_col=values(your_col)
Quoting the relevant part :
You can use the VALUES(col_name)
function in the UPDATE clause to
refer to column values from the
INSERT portion of the INSERT ... ON
DUPLICATE KEY UPDATE statement.
In other words,
VALUES(col_name) in the ON
DUPLICATE KEY UPDATE clause refers to
the value of col_name that would be
inserted, had no duplicate-key
conflict occurred. This
function is especially useful in
multiple-row inserts.
Then, as a sidenote, you must escape your strings using the function that matches your API -- probably mysql_real_escape_string -- and not the generic addslashes, which doesn't know about the specificities of your database engine.
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just