I get a mysql error when using mysql_query() [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
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') ");

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);
}
$type can be "s" for string, "i" for integer, "d" for double and "b" for blob.
The question marks ? have to be as many as the values you want to insert to your database.
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()

In cases such as this, it's helpful to see the generated query for yourself. Do this:
echo "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') ";
And then check the query that is generated. I bet you'll find your error if you look carefully.

Related

I can't insert data from php to mysql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
In my Mysql I have this table. And I want to send data
Id is autoincrement
Id
insertId
invoceTaxApplayId
sumOfDist
if (isset($_POST['basic'])) {
$user_string = $_POST['basic'];
$basic = json_decode($user_string);
foreach ($basic as $key => $value){
$sql2 = "INSERT INTO `insert_tax_applay_map`( `insertId`, `invoceTaxApplayId`, `sumOfDist`) VALUES ('$value','', 5)";
echo $sql2; //printed
echo $key;
}
exit();
}
I can see echos, but data isn't sent to mysql.
You can fix the issue of not executing and your serious SQL injection bug with one simple trick: Prepared statements with placeholder values!
if (isset($_POST['basic'])) {
$user_string = $_POST['basic'];
$basic = json_decode($user_string);
// Prepare your database query with placeholder values
$stmt = $db->prepare("INSERT INTO insert_tax_applay_map (insertId, invoceTaxApplayId, sumOfDist) VALUES (:insertId, :invoiceTaxApplayId, :sumOfDist)");
// For each entry...
foreach ($basic as $key => $value) {
// ...execute the statement with that particular set of values.
$stmt-execute([
'insertId' => $value,
'invoiceTaxApplayId' => '',
'sumOfDist' => 5
]);
}
exit();
}
This example uses PDO but can easily be adapted to mysqli or whatever you're using.
Tip: For general guidance on PHP, see PHP the Right Way for more resources.

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables 11 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
My code against SQL injection isn't working (error message in title).
I simplified my code, but its still not working.
<?php
include "conf.php";
$db = new mysqli($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS, $MYSQL_DB);
$ltime =10;
$url= 1;
$title =2;
$result = $db->prepare("INSERT INTO links VALUES ('', ?, ?, ?)");
$result->bind_param('ss', $url, $title, $ltime);
$result->execute();
I created DB and all variables are integer, first value is ID and it is created with an auto Increment flag.
You have to put three "s" in the bind_param method, because there are three variables to bind
$result = $db->prepare("INSERT INTO links VALUES (NULL, ?, ?, ?)");
$result->bind_param('sss', $url, $title, $ltime);
I's also better to pass a null NULL value for the autoincremented field instead of an empty string
You have:
$result->bind_param('ss', $url, $title, $ltime);
but it should be
$result->bind_param('sss', $url, $title, $ltime);
The first function parameter of
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
determines the type of each single bound variable/sql-parameter. You have three sql-parameters, so your first function parameter must specify three types (three times s in this case), not just two.
And on a side-node: I'd rather assign the return value of mysqli::prepare to a variable with the name $statement than $result.

Query breaks when data contains single quote [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hello guys i need your help with this php code,
and trying to create survey name using text box..but what happens is that $survey_name = $_POST['txtSurveyName']; does not save any input with e.g. Department's but it saves Departments.
I noticed that the problem is with the single quotes, how can write this code to accept the single quotes?
here is the full code:
**$survey_name = $_POST['txtSurveyName'];**
$survey_status = $_POST['status'];
// Save question
$sql = "INSERT INTO survey(survey_name, status) VALUES('{$survey_name}','{$survey_status}')";
$result = mysql_query($sql);
// Redirect to landing page
As much as I hate this answer I will still tell you that you need to escape your strings:
$survey_name = mysql_real_escape_string($_POST['txtSurveyName']);
But I would suggest using PDO or MySQLi prepared statements. Better for your security.
So easy with PDO:
//prepare query
$stmt = $pdoInstance->prepare('INSERT INTO survey(survey_name, status) VALUES(:name, :status)');
//bind params
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':status', $status, PDO::PARAM_STR);
if ($stmt->execute()) {
//success
}
This way your code is more secure and I feel better that I did not suggest something horrible.
From: http://us2.php.net/mysql_real_escape_string
$survey_name = $_POST['txtSurveyName'];
$survey_status = $_POST['status'];
$sql = sprintf("INSERT INTO survey(survey_name, status) VALUES('%s','%s')'",
mysql_real_escape_string($survey_name),
mysql_real_escape_string($survey_status));
$result = mysql_query($sql);
Change your query to escape specials chars :
$sql = "INSERT INTO survey(survey_name, status) VALUES(\"{$survey_name}\",\"{$survey_status}\")";
or
$sql = "INSERT INTO survey(survey_name, status) VALUES('".addslashes($survey_name)."','".addslashes($survey_status)."')";

mysqli_stmt_bind_result() number of variables doesnt match? help me how to count [duplicate]

This question already has an answer here:
PHP mysqli prepare statement not working
(1 answer)
Closed 1 year ago.
I simply want to select a bunch of fields from a data base - as I have done it a lot of times before... But somehow I get this error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement
But I count exactly 14 columns, so why when I add 14 variables does it throw this error?
public function get_invitation_fields()
{
$this->fields_db = array();
include('system/mysqli_db.php'); //db connection opens here
$statement="SELECT
invitation_ID,
recipient,
text,
name,
usr_ID,
deleted,
send_date,
resend_date,
last_date,
status,
register_date,
verify_date,
redeem_date
trans_ID
FROM invitations WHERE email=?";
if ($stmt = mysqli_prepare($db, $statement))
{
mysqli_stmt_bind_param($stmt, "s", $this->email);
if(!mysqli_stmt_execute($stmt))
{echo mysqli_stmt_error($stmt); echo mysqli_error($db); }
mysqli_stmt_bind_result($stmt,
$this->fields_db['invitation_ID'],
$this->fields_db['recipient'],
$this->fields_db['text'],
$this->fields_db['name'],
$this->fields_db['usr_ID'],
$this->fields_db['deleted'],
$this->fields_db['send_date'],
$this->fields_db['resend_date'],
$this->fields_db['last_date'],
$this->fields_db['status'],
$this->fields_db['register_date'],
$this->fields_db['verify_date'],
$this->fields_db['redeem_date'],
$this->fields_db['trans_ID']
); //PHP points the error to this line.
mysqli_stmt_fetch($stmt);
$this->invite_fields_db = $this->fields_db;
mysqli_stmt_close($stmt);
}
else
{
echo mysqli_stmt_error($stmt);
echo mysqli_error($db);
}
mysqli_close($db);
}
Can anyone see what's wrong?
Just don't use mysqli with it's bind_result, which indeed makes you ask other people to count your variables.
Either use PDO, which will make your code as short as
public function get_invitation_fields($email)
{
global $pdo; // connection should be opened ONCE at the beginning of the whole app
$sql = "SELECT * FROM invitations WHERE email=?";
$stm = $pdo->prepare($sql);
$stm->execute(array($email));
return $stm->fetch(); // values have to be RETURNED, not assigned
}
or at least use get_result() to get a familiar array from the query, without need of binding every variable manually, though it's not guaranteed to work.

PHP PDO Prepared Statements and Value Binding Gives Invalid Parameter Number Error

I'm having a slight problem with the PHP PDO library and prepared statements. As far as I can see the prepared statement below should work but it doesn't, instead I get: "PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens".
My PHP code for this section looks like:
$sql = 'INSERT INTO '.POLYGON_TABLE.' (user_id, polygon, polygon_type) VALUES (:userId, PolygonFromText(\'POLYGON((:polygonArea))\'), :polygonType)';
$sth = $this->pdo->prepare($sql);
$sth->bindValue(':userId', $polygon->getUserId(), \PDO::PARAM_INT);
$sth->bindValue(':polygonArea', $polygon->getPolygonAsText(), \PDO::PARAM_STR);
$sth->bindValue(':polygonType', $polygon->getPolygonType(), \PDO::PARAM_STR);
if($sth->execute()) {
return true;
} else {
return false;
}
I have done a var_dump of $polygon->getUserId(), $polygon->getPolygonAsText() and $polygon->getPolygonType() and get the following:
string(1) "1"
string(226) "53.897910476098765 -1.739655277929728, 53.865530797116 -2.080231449804728, 53.67235280490181 -2.006073734960978, 53.68862047002787 -1.621552250585978, 53.89305512284903 -1.539154789648478, 53.897910476098765 -1.739655277929728"
string(7) "commute"
The issue is with $polygon->getPolygonAsText() as commenting out this particular bindValue call and the PolygonFromText(\'POLYGON((:polygonArea))\') from the SQL statement causes the query to work.
I'm now completely at a loss. Anyone know what's wrong here? I can't see anything wrong with the text contained within $polygon->getPolygonAsText(). I have searched high and low for a solution to this and spent several hours this evening tinkering with the code but to no avail.
I have even tried the suggestions in these 2 stack overflow topics but they didn't work either:
Invalid parameter number on PDO Prepared Statement
PHP PDO prepared statements
Any help would be much appreciated...
Did you try passing in the entire expression as the bind value?
$sql = 'INSERT INTO '.POLYGON_TABLE.' (user_id, polygon, polygon_type) VALUES (:userId, PolygonFromText(:polygonArea), :polygonType)';
$sth = $this->pdo->prepare($sql);
$area = sprintf("POLYGON((%s))", $polygon->getPolygonAsText());
$sth->bindValue(':userId', $polygon->getUserId(), \PDO::PARAM_INT);
$sth->bindValue(':polygonArea', $area, \PDO::PARAM_STR);
$sth->bindValue(':polygonType', $polygon->getPolygonType(), \PDO::PARAM_STR);
It appears that you're trying to use a named parameter inside a string:
PolygonFromText(\'POLYGON((:polygonArea))\')
This would be akin to doing something like this:
UPDATE foo SET bar = 'blah blah :wontwork blah blah'
What you should try instead is binding the whole string in the query:
PolygonFromText(:polygonArea)
And then including the rest of the string in the bound value:
$sth->bindValue(':polygonArea', 'POLYGON((' . $polygon->getPolygonAsText() . '))', \PDO::PARAM_STR);
Last resort you could do this:
$sql = "INSERT INTO ".POLYGON_TABLE." (user_id, polygon, polygon_type) "
."VALUES (:userId, PolygonFromText('POLYGON(". $polygon->$getPolygonAsText
.")'),:polygonType)";
But I think you should try the ? params first and see how that goes.
$sql = "INSERT INTO ".POLYGON_TABLE." (user_id, polygon, polygon_type) "
."VALUES (?, PolygonFromText('POLYGON(?)'), ?);";
$data = array($polygon->getUserId(), $polygon->getPolygonAsText(), $polygon->getPolygonType());
$query->execute($data);
Btw, I also think those single quotes around the POLYGON(?) function are dodgy... usually you don't quote a method call do you?

Categories