This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 1 year ago.
Update query not taking integer variable ($user):-
$user = $_POST["user"];
$user = (int)$user;
$sql = "UPDATE users_meta
SET
`meta_value` = '$plan_end'
WHERE
`user_id` = $user AND
`meta_name` = 'plan_end'";
$conn->query($sql);
user_id column in mysql database is set to int datatype.
When I simply put a number instead of the variable, it works:-
WHERE
`user_id` = 37 AND ...
I also tried without converting the number from string to int, and its not working. I have a feeling that it has something to do with quotes, so I played around with it based on suggestions online, but none worked.
As per based on my knowledge if database field is of Int type then it cannot accept character/string values even you are converting them into type of integer. You have to modify the database field to varchar or you have to pass only numeric values to the database field. Hope this suggestion may solve your problem.
Hi I have tested your query on my local it works fine so I don't think there is any thing wrong with you query.
<?php
$mysqli = new mysqli("localhost","root","","test_table");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if(#$_POST["user"])
{
$user = $_POST["user"];
$tasone = $_POST["tasone"];
$user = (int)$user;
$sql = "UPDATE test_table SET `TAS_ONE` = '$tasone' WHERE `user_id` = $user and `TAS_TWO`='dsadsa'";
$mysqli->query($sql);
}
?>
<form action="" method="post">
<input type="text" id="user" name="user" value=""><br>
<input type="text" id="tasone" name="tasone" value=""><br>
<input type="submit" value="Submit">
</form>
CREATE TABLE `test_table` (
`USER_ID` int(9) NOT NULL,
`TAS_ONE` varchar(200) NOT NULL,
`TAS_TWO` varchar(200) NOT NULL,
`TAS_THREE` varchar(200) NOT NULL,
`TAS_FOUR` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I was trying to make a sql database and i have faced some issues regarding INSERT INTO TABLE.
I have noticed that sql is not allowing me to insert data in a table if the name of Database is u759286173 i am able to insert data into table using any other name but this particular (u759286173) database name is not allowing me to insert data in table
I have tried various database names which works
759286173
759286173_quebec
759286173_grvnaz
u_grvnaz
Can someone please explain me that why data is not inserting in table when i allow the database name to be u759286173
My Database name : u759286173
My Table name : mydb
Please reply if u face the same issue or have a solution.
Any help is appreciated.
My Code
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "u759286173";
$dbHost = " localhost";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
other code
<?php
session_start();
include 'dbh.inc.php';
if (isset($_POST) & !empty($_POST)) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO mydb (first, last, email, message)
VALUES ('$first', '$last', '$email', '$message');";
mysqli_query($conn, $sql);
header("location: ../signup.php?send=success");
} else {
header('location: ../failed.php');
exit();
}
?>
Form Code
<!DOCTYPE>
<html>
<body>
<form class="registerform" action="includes/contact.inc.php" method="POST">
<input type="text" placeholder="first" name="first" required/>
<input type="text" placeholder="last" name="last" required/>
<input type="email" placeholder="E-mail ID" name="email"/>
<input type="text" placeholder="message" name="message" required/>
<button name="submit" type="submit">Create</button>
</form>
</body>
</html>
=Database u759286173
CREATE TABLE IF NOT EXISTS `mydb` (
`id` int(11) NOT NULL,
`first` varchar(32) NOT NULL,
`last` varchar(32) NOT NULL,
`email` varchar(50) NOT NULL,
`message` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The INSERT statement does not provide a value for the id column.
The id column is defined to be NOT NULL and does not have AUTO_INCREMENT property. (And we assume there isn't a BEFORE INSERT trigger that assigns a value to NEW.id
Given the table definition, we expect that when the INSERT statement is executed, MySQL will issue
Error Code: 1364
Field 'id' doesn't have a default value
(This could be a Warning rather than Error with some settings of sql_mode.)
Most important is that we check for MySQL error condition; this will provide the information we need in order to determine what the problem is.
At the top of the script, enable PHP and mysqli error reporting:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
That will get use the information we need when a MySQL error occurs.
I inserted data through the phpmyadmin into my table. It shows me the query it uses so I copied and pasted it into my php code.
My Php code is suppose to be submitting a form and I am trying to get $_POST('name') into the query.When I run the code it fills everything out but the version_name field where name goes.
Funny thing is im using the same MYSQL query that inserts it correctly on the phpmyadmin.
I have moved on to trying a random name not the POST to see if it submits but i keep getting a blank... any suggestions?
$sql = "INSERT INTO `Prototype`.`Version` ('version_id', `version_name`, `version_status`, `created_date`, `created_by`) VALUES ('','A', 'A', CURRENT_TIMESTAMP, NULL);";
this is the Insert part, and I have also tried removing the version_id since it is autoincramented but no help.
the first row is what the result looks like when submitted from my php. the second row is when I insert it right from phpmyadmin.
Any help getting version_name to be submitted from my php would be wonderful!
edit----
Heres my php code
<?php
// Retrieve form data
$name = $_POST['name'];
if (!$name) {
echo "save_failed";
return;
}
$db = array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'Prototype',
);
$link = #mysql_connect($db['host'], $db['login'], $db['password']);
if (!$link) {
echo "save_failed";
return;
}
mysql_select_db($db['database']);
// Clean variables before performing insert
$clean_name = mysql_real_escape_string($name);
// Perform insert
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ( 'A', 'A', CURRENT_TIMESTAMP, NULL);";
if (#mysql_query($sql, $link)) {
echo "success";
#mysql_close($link);
return;
} else {
echo "save_failed";
#mysql_close($link);
return;
}
?>
firs thing first $_POST('name'); is nothing $_POST['name']; is right. Now answer to your question use following query.
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ('A', 'A', CURRENT_TIMESTAMP, NULL)";
I have also checked it on my own table made from structure provided by you.
it's query is given below.
CREATE TABLE `proto` ( `version_id` int(3) NOT NULL AUTO_INCREMENT, `version_name` varchar(45) NOT NULL, `version_status` varchar(45) NOT NULL, `created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_by` varchar(45) DEFAULT NULL, PRIMARY KEY (`version_id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
Below code is for you to submit it via php.
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host=".HOST.";dbname=".DBNAME.";charset=utf8", USERNAME, PASSWORD, $options);
$query = $db->prepare("INSERT INTO `Prototype`.`Version`
(`version_name`,
`version_status`,
`created_date`,
`created_by`)
VALUES
('A',
'A',
CURRENT_TIMESTAMP,
NULL)");
$result = $query->execute();
return $result ? true : false;
This many be by the by, and not an answer to your question but in Mysql 4 this would work:
An auto increment value can be
left out completely, if you state named fields
NULL
0
'' (empty string)
From Mysql 5 the last one will not work.
It was an undocumented feature of Mysql 4 which was removed for Mysql 5.
It was an error with the server. I deleted the database and started from scratch and it solved the issue. Almost went as far as uninstalling and reinstalling xampp.
I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";
I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.
i need to perform a name search in the database based on a set of keywords. the result should be accent sensitive and case insensitive.
following the solution i found here plus few modifications to allow case insensitivity, i used the following code:
$sql = "SELECT name FROM table_names WHERE LOWER(name) LIKE _utf8 '%".strtolower($keyword)."%' COLLATE utf8_bin";
this does not work for me when the search keyword contains accents. but the strange thing is that this query works well in phpMyAdmin (but i read somewhere that this shouldn't be reliable). what could be the problem here?
UPDATE:
i revised my code to:
$sql = "SELECT name FROM table_names WHERE LOWER(name) LIKE LOWER(_utf8 '%$keyword%') COLLATE utf8_bin";
but i still have no results.
thanks!
You can try to echo the sql being executed and check if the accents are there.
My guess they are not...
[EDIT]
Can you try this:
php.
<html>
<head>
</head>
<body>
<form action="" method="get">
<input name="name" type="text"/>
<input type="submit" value="go"/>
</form>
<?php
if (!empty($_GET['name'])) {
$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset('latin1');
$_GET['name'] = utf8_encode($_GET['name']);
if ($result = $mysqli->query('select * from dummy where LOWER(name) LIKE _utf8 \'%' . $_GET['name'] . '%\' COLLATE utf8_bin')) {
while ($obj = $result->fetch_object()) {
var_dump($obj->name);
}
}
$mysqli->close();
}
?>
</body>
</html>
mysql: (doesn't matter)
CREATE TABLE `dummy` (
`id` int(11) NOT NULL,
`name` varchar(45) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin5$$
This one works for me...