Mysql Syntax Error... or is it the PHP? - php

Can someone help me figure out what is wrong with this function??
I am getting a mysql syntax error...
function category_exists($name) {
$name = mysql_real_escape_string($name);
$query = mysql_query("SELECT COUNT(1) FROM 'categories' WHERE 'name' = '{$name}'");
return (mysql_result($query, 0) == '0')? false : true;
}

You should not have quotes around your table and column name (categories, name). If you need to escape a table or column names, you should use backquotes (`). IE:
$query = mysql_query("SELECT COUNT(1) FROM `categories` WHERE `name` = '{$name}'");

function category_exists($name) {
$name = mysql_real_escape_string($name);
$query = mysql_query("SELECT COUNT(1) FROM `categories` WHERE `name` = '{$name}'");
return (mysql_result($query, 0) == '0')? false : true;
}
You need either backquotes (`) or NO quotes around table names and field names.

Strings are quoted. Object names (tables, columns...) are not.

Try changing the query to
"SELECT COUNT(*) FROM 'categories' WHERE name = '$name'"

Related

Model PHP SQL IF Statement Not Working

I am unsur why the below statement is not working basically in a nutshell I am wanting it to run the $result statement if only the $product_id is not found in the $images table. Is it is found I would like it to then run the inner statement.
Both statements do work via phpMyAdmin and the $result statement works when just using $this->db->query
Code:
public function product_delete($product_id)
{
$table = $this->_table_products;
$images = $this->_table_product_images;
$result = $this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
if(mysqli_num_rows($result) !== 0)
{
$this->db->query("DELETE FROM $table WHERE $table.id = '$product_id'");
}else{
$this->db->query("DELETE FROM $table INNER JOIN $images ON $table.id = $images.product_id WHERE $images.id = $product_id");
}
}
You have to use {} around variable name in query. Also use != instead of !==
$result = $this->db->query("SELECT `id` FROM {$table} WHERE {$table}.id ='$product_id'");
if(mysqli_num_rows($result) != 0)
{
$this->db->query("DELETE FROM {$table} WHERE {$table}.id = '$product_id'");
}else{
$this->db->query("DELETE FROM {$table} INNER JOIN {$images} ON {$table}.id = {$table}.product_id WHERE {$images}.id = $product_id");
}
Change !== to !=
if(mysqli_num_rows($result) != 0)
{
$this->db->query("DELETE FROM $table WHERE $table.id = '$product_id'");
}
else
{
$this->db->query("DELETE FROM $table INNER JOIN $images ON $table.id = $images.product_id WHERE $images.id = $product_id");
}
If you want to check the images table, you should query the table ${images}, not ${table}. Also, if you are only interested in finding out how many matching rows there are, it's best to use the COUNT() function in MySQL. That way you always get one row instead of potentially 100,000s. Using the function mysqli_num_rows() has the disadvantage that you're loosing the flexibility that the CodeIgniter database class introduces.
So your code should be something like
$result = $this->db->query("SELECT COUNT(*) `cnt` FROM ${images} WHERE ${images}.product_id ='$product_id'");
$row = $result->row();
if($row['cnt'] != 0) {
// found something
If the variable name is unclear in a string, you can use brackets to tell PHP what you want. "${foo}bar" means that the variable is $foo and bar is just some string to append to the variable content. It also helps to improve readability. And I changed !== to != because I'm not familiar enough with CI and I do not know if the value will be an integer or the string representation of an integer.

PDO returns wrong value for select statement

I've a PHP application that works with MySQL through PDO. I have a table with different records and I have to prevenet inserting a duplicate one. But when I want to check existing items, select statement does not return a true value. This is my code:
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
if ($q->fetchColumn() == 0)
{
...
I also tested this one:
$sql = "SELECT id FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
$rows = $q->rowCount();
if ($rows == 0)
{
...
Imagine $title=1. I have 4 records with this value. But I can not see anything in SELECT statement. What is wrong here ?
try this: (don't wrap the value of the title with single quotes)
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = ? ";

Select mysql in PHP with 2 vars

How i can make this whitout php notice error:
$id = $_GET['id'];
$name = $_POST['name'];
$sql = mysql_query("SELECT * FROM table WHERE id = '$id' or name = '$name');
And how i can do one search in many tables at once.
Thank you
Your query string is incomplete. You need a closing double quote at the end.
$sql = mysql_query("SELECT * FROM table WHERE id = '$id' or name = '$name'");
^ ^
To search many tables at once, add more tables separated by a comma.
"SELECT table1.field, table2.field FROM table1, table2"
$id = isset($_GET['id']) ? $_GET['id'] : null;
$name = isset($_POST['name']) ? $_POST['name'] : null;
if($id !== null || $name !== null) {
$sql = mysql_query("SELECT * FROM table WHERE id = '$id' or name = '$name'");
}

Unsolvable MySQL 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 'repeat = 'week', location = 'Patowmack Farm', location_link = 'http://maps.googl' at line 1
I keep getting this message for both my update script (show above), and my insert script. I cannot find why it's doing this! Anyone available to help?
My update code:
foreach($_POST['enabled'] as $key => $value ) {
$key = mysql_real_escape_string($key);
if ($_POST['delete'][$key]=='1') {
mysql_query("DELETE FROM upcoming WHERE id='$key'") or die(mysql_error());
}
else {
$title = mysql_real_escape_string($_POST['title'][$key]);
$date = mysql_real_escape_string(($_POST['date'][$key]));
$repeat = mysql_real_escape_string($_POST['repeat'][$key]);
$group = mysql_real_escape_string($_POST['group'][$key]);
$group_link = mysql_real_escape_string($_POST['group_link'][$key]);
$location = mysql_real_escape_string($_POST['location'][$key]);
$location_link = mysql_real_escape_string($_POST['location_link'][$key]);
$notes = mysql_real_escape_string($_POST['notes'][$key]);
$enabled = mysql_real_escape_string($_POST['enabled'][$key]);
mysql_query("UPDATE upcoming SET title = '$title', date = '$date', repeat = '$repeat', location = '$location', location_link = '$location_link', group = '$group', group_link = '$group_link', notes = '$notes', enabled = '$enabled' WHERE id = '$key' LIMIT 1") or die(mysql_error());
}
}
Have you tried changing the query to:
mysql_query("UPDATE `upcoming` SET `title` = '$title', `date` = '$date', `repeat` = '$repeat', `location` = '$location', `location_link` = '$location_link', `group` = '$group', `group_link` = '$group_link', `notes` = '$notes', `enabled` = '$enabled' WHERE `id` = '$key' LIMIT 1") or die(mysql_error());
Edit: And as others have stated; you are using reserved words. I recommend always using the ` symbol. (This can be found at the top left for most keyboards: under the escape key, above the tab key, to the left of the number 1 key.)
GROUP and REPEAT are reserved keywords in MySQL so you have to "escape" it with backticks:
`group` = '$group'
`repeat` = '...'
Also I'm making an assumption here, but you shouldn't wrap $key in quotes because it is an integer value. Also make sure you type cast it to an int by doing int($key).
repeat is a keyword in MySQL use back ticks repeat to use this.
Repeat is a mySQL reserved word: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Try surrounding your column names with backticks.

How can I check if mysql table column even exists?

How can I check if mysql table field even exists ?
The column name is 'price' and I need to see if it exists.
Haven't understood really how the 'EXISTS' works...
Any examples or ideas ?
Thanks
In PHP:
$fields = mysql_list_fields('database_name', 'table_name');
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if (!in_array('price', $field_array))
{
$result = mysql_query('ALTER TABLE table_name ADD price VARCHAR(10)');
}
This should also help you:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
ALTER TABLE TEST ADD TEST_DATE DATETIME
END
Or you can do:
Show columns from table like 'string';
There has been a similar question posed on SO here before.
Try:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME = 'Price')
BEGIN
-- do something, e.g.
-- ALTER TABLE TEST ADD PRICE DECIMAL
END
Another way of doing it in PHP:
$chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(isset($mycol['price']))
echo "Column price exists! Do something...";
Well, one way is to do:
select price from your_table limit 1
If you get an error:
#1054 - Unknown column 'price' in 'field list'
then it does not exists.
I found this very useful. It will list all the tables that has that column name.
SELECT table_name,
column_name
FROM information_schema.columns
WHERE column_name LIKE '%the_column_name%'
well here is a function to check out if a particular column exists or not.
public function detect_column($my_db, $table, $column)
{
$db = mysql_select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'"; //query
$result = mysql_query($sql); //querying
if(mysql_num_rows($result) == 0) //checks the absence of column
echo "column $column doesn't exist !";
// write your code here!
else
echo "column $column exists!";
}
well if you are designing a frame work, then this function may come to your aid. This function checks for the presence of column when $flag is set to '1' and absence of column when $flag is set to '0'.
public function detect_column($my_db, $table, $column, $flag)
{
$this->select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == $flag)
return true;
else
return false;
}
You could get a description of all the column in your table.
desc your_table;
I just done something like this using this function for Wordpress, this for update tables that having new chnages on it
public function alterTable() {
$table_name = $this->prefix . $this->tables['name'];
$select = "select * from `{$table_name}` where 0=0 limit 1;";
$query = $this->db->get_results($select, ARRAY_A);
if (isset($query[0]) && !key_exists('adv', $query[0])) {
$sql = "ALTER TABLE `{$table_name}` ADD `me` INT NULL DEFAULT NULL ;";
$this->db->query($sql);
}
}

Categories