-1

whats wrong here????

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 'desc from materials' at line 1

this is the code

<?php
$serverName ="localhost";
$dbname="inventory";
$conn = mysql_connect($serverName,"root","");
if(!$conn) die("Connection error". mysql_connect_error());
else echo "connected successfully";
$desc = mysql_query("select desc from materials where code = 123",$conn ) or  die (mysql_error());
mysql_close($conn); ?>
  • 5
    add a `back-tick` you have a column named `desc`. "select \`desc\` from materials where code = 123" – roullie Jan 26 '16 at 02:17
  • 1
    `desc` is a reserved word, basically because it is the keyword in a sort `order by x desc` so as you have picked a reserved word for this column name you have 2 options. 1) the prefered oprion, use another name for this column and 2) wrap the column name is backticks `select \`desc\` from materials where code = 123` – RiggsFolly Jan 26 '16 at 02:18
  • The third option is to qualify the reference to the column name with the tablename or table alias. For example: **`select materials.desc from materials where`** – spencer7593 Jan 26 '16 at 02:56

2 Answers2

1

You are using reserved words, so need to escape.

select `desc` from materials where code = 123

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers. This section describes the permissible syntax for identifiers in MySQL. Section 9.2.2, “Identifier Case Sensitivity”, describes which types of identifiers are case sensitive and under what conditions.

The identifier quote character is the backtick (“`”):

mysql> SELECT * FROM `select` WHERE `select`.id > 100;

An identifier may be quoted or unquoted. If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

It is recommended not to use reserved words.

calraiden
  • 1,686
  • 1
  • 27
  • 37
-1

First of all, you have not selected any database for performing queries. Add this line for selecting database after 6th line:

else echo "connected successfully";

$dbconn = mysql_select_db( $dbname , $conn);
if (!$db_conn) {
   die ('Can\'t use this database: ' . $dbname . mysql_error());
}
$desc = mysql_query("select `desc` from materials where code = 123",$conn ) or  die (mysql_error());
//desc is a reserved keyword in mysql, so you ought to put it between the ` symbol
Birendra Gurung
  • 2,168
  • 2
  • 16
  • 29