bantandor bantandor - 5 months ago 10
MySQL Question

I get a mysql error when using mysql_query()

I am having 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 'Not, Fotograf, Tarih) values ('','','','','','','','TC','','','','Ev' at line 1"

(I am using wamp6.4 that keeps asking "mysqli")

What can be wrong?

My PHP code:



$ekle = mysql_query("INSERT INTO kayitliste (AdayNo, KimlikNo, Ad, Soyad, MezunLise, DiplomaDerece, TelefonNo, Uyruk, VeliAdSoyad, VeliTelefon, Adres, Ulasim, Bolge, Yurt, Bolum, TercihSirasi, Burs, Dekont, Kimlik, Diploma, Odenen, Sinif, Not, Fotograf, Tarih)
VALUES ('$AdayNo','$KimlikNo','$Ad','$Soyad','$MezunLise','$DiplomaDerece','$TelefonNo','$Uyruk','$VeliAdSoyad','$VeliTelefon','$Adres','$Ulasim','$Bolge','$Yurt','$Bolum','$TercihSirasi','$Burs','$Dekont','$Kimlik','$Diploma','$Odenen','$Sinif','$Not','$Fotograf','$Tarih') ");

Answer

mysql is deprecated. You should be using either mysqli or PDO with a parameterized query as shown below:

Mysqli:

$link = mysqli_connect("localhost", "root", "");
mysqli_select_db("Your database");

if ($stmt = mysqli_prepare($link, "INSERT INTO `kayitliste` VALUES (?, ?, ?, ?, ?)")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, $type, $AdayNo, $KimlikNo, $Ad, $Soyad, $MezunLise);

    /* Execute query */
    mysqli_stmt_execute($stmt);

    /* Bind result variables */
    mysqli_stmt_bind_result($stmt, $AdayNo, $KimlikNo, $Ad, $Soyad, $MezunLise);

    /* Close statement */
    mysqli_stmt_close($stmt);
}
  1. $type can be "s" for string, "i" for integer, "d" for double and "b" for blob.

  2. The question marks ? have to be as many as the values you want to insert to your database.

  3. In your case of many values, you should know what type each value is and write $type = "iisss", with as many letters as your values. Since your variables are in a language I do not know I assummed that these ending in No are integers and the other three strings.

PDO:

$sql = 'INSERT INTO `kayitliste` (`AdayNo`, `KimlikNo`, `Ad`, `Soyad`, `MezunListe`)
VALUES (:AdayNo, :KimlikNo, :Ad, :Soyad, :MezunListe)");

$sth = $dbh->prepare($sql);
$sth->bindParam(':AdayNo', $AdayNo, PDO::PARAM_INT);
/* Do that for every parameter */
/* PDO::PARAM_INT is the equivalent of "i" of mysqli in PDO. */
$sth->execute()
Comments