Hi! My table structure looks like this:
CREATE TABLE IF NOT EXISTS `search` (
`key` varchar(255) NOT NULL,
`id` int(15) NOT NULL auto_increment,
UNIQUE KEY `key` (`key`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
And this is how I try to add data into my table:
$stmt = $mysqli->prepare("INSERT INTO search(key) VALUES (?)");
$stmt->bind_param('s',$keyword);
$stmt->execute();
$stmt->close();
This is what I got:
Call to a member function bind_param() on a non-object
But it works when I do this:
$stmt = $mysqli->prepare("INSERT INTO search VALUES (?,NULL)");
$stmt->bind_param('s',$keyword);
$stmt->execute();
$stmt->close();
Is there any other way besides putting NULL to the VALUES?
is there any necessity that i should put NULL to auto increments?
No.
And there is no necessity in finding an answer by means of wild guess either.
You have to get the error message instead.
For which purpose always have this line right before connecting to mysqli:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
speaking for the certain query, key is a mysql keyword and have to be quoted in backticks
INSERT INTO search(`key`) VALUES (?)
Related
So I have this PHP code to create a table. It should create a table called test101_list1, but instead it creates a table called 'test101'_'list1'. Without the backslash, PDO will see it as :username_ instead of :username. Also, I'd like to get rid of the quotes around the username and list name, but I still want to sanitize the input, as it uses user input. How can I do this?
$stmt = $db->prepare("CREATE TABLE `lists`.`:username\_:listname` ( `id` INT(10) NOT NULL AUTO_INCREMENT , `lang1` TEXT NOT NULL , `lang2` TEXT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci;");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':listname', $listname);
$username = "test101";
$listname = "list1";
$stmt->execute();
In my MySQL database I have a table "table1" with unique constraint set on column "name" - I want to prevent duplicate names.
If there's already name 'John' in table this code:
$db=new mysqli(...);
$sql="INSERT INTO table1 SET id=10,name='John'";
if(!$db->query($sql))
{
if($db->errno==1062)
{
throw new InsertNonUniqueException(...);
}
else
{
throw new InsertException(...);
}
}
should throw InsertNonUniqueException() (my own exception). Instead, it throws InsertException().
Execution of query returns false and execution enters the if() loop. Also $db->row_affected is -1 but problem is that $db->errno is always O (it should be 1062)!!! So I can't detect that my insert error was caused by violating unique key constraint on name column!
I don't know why mysqli does not return 1062 code when unique key constraint violation occurs!
I can't leave a comment, thus going to ask you here.
Please provide the result of SHOW CREATE TABLE table1;
I can't reproduce your problem using your code and next table:
CREATE TABLE `table1` (
`name` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Am I the only one around here that thinks you have an error in your SQL syntax?.. There is no room for SET in INSERT INTO, because you can only use SET in UPDATE statements (assuming you habe MySQL in version 5.5 or below).
INSERT INTO syntax is like the following (as described in the docs):
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
OR
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
Try it like this:
<?php
$sql="INSERT INTO table1 (id, name) VALUES ('10', 'John')";
...
step 1
make sure that the table has a unique key
SHOW CREATE TABLE table1
expected result
CREATE TABLE `table1` (
`id` INT(11) default NULL,
`name` varchar(11) COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
if there is UNIQUE KEY name (name) we have a unique key
step 2
try to change your code
$db = new mysqli(...);
// first insert
if( !$db->query("INSERT INTO table1 (id, name) VALUES (10, 'John')") ) {
throw new Exception($db->error);
}
// second insert (for me raise: Duplicate entry 'John' for key 'name')
if( !$db->query("INSERT INTO table1 (id, name) VALUES (11, 'John')") ) {
throw new Exception($db->error);
}
Please, try these two steps
Side note: if you have name and id as duplicates, only the first duplicate encountered will be returned in the message.
The only issue i have with your code is that:
having setup your table and columns.
I setup a unique index on the table. I did .. stuff on a two column table that ensure it works.
You missed the 'new'
keyword when you 'throw exceptions'.
this is the only error with your posted code that i could find.
i.e: throw new Exception('Division by zero.'); // example taken from PHP manual.
My query returns with null in my php code , but when I enter the same query into phpmyadmin it returns the row to which it belongs. Here is the database I am using
CREATE TABLE `payment`.`users`(
`u_id` int(12) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`passwd` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`email`)
) ENGINE=MyISAM;
and here is the code i am using that is returning null when it clearly works in phpmyadmin.
function getUserId($email, $passwd) {
$mysqli = db_connect();
$query = "SELECT `u_id` FROM `payment`.`users` WHERE `email`='$email' AND `passwd`='$passwd' ORDER BY 1";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
$stmt->bind_result($u_id);
while ($stmt->fetch()) {
return $u_id;
}
}
}
The thing is that you are using variables in your php code to set the values. In phpMyAdmin you're inserting values directly, therefore the problem may be in the values inserted.
First of all use PDO's bindParam() or mysqli's bind_param() statements as they sanitize inputs and help you avoid SQL Injections.
Second good thing about using prepared statements and binding params is that you can specify the type of the data being binded to to the query which in most cases will fix such problems. Though in your case you're probably inserting strings.
<?php
mysql_query("CREATE TABLE IF NOT EXISTS test.$p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
INSERT INTO $p ( `title`, `colum`, `ord`, `tex`, `search`, `count`, `order`) VALUES
('$a', '$b', '$c', '$d', '$f', '$h', '$g'); ");
?>
I am working in a PHP language . $r is my database and $p is my table name
In this I am creating a table , if table is not created and if the table is created then i want to insert the values in the respective column given above but I am not good at mysql_query so I don't know where to add the insert query
I found a solution for my problem but this code is properly working in the phpmyadmin but when i run this code using php , it show me nothing inthe database
You can not execute two queries with a single mysql_query().
Make another call to mysql_query() with the INSERT query as the parameter.
If you absolutely must execute multiple queries in a single function call, change your mysql engne to mysqli, then use mysqli_multi_query() like so:
mysqli_multi_query ($link, 'query1;query2;query3;...');
Please keep in mind that although both approaches issue queries sequentially, their execution is not atomic. If you need atomicity, use a TRANSACTION.
The 13.1.17. CREATE TABLE Syntax can do something like:
CREATE TABLE IF NOT EXISTS `table1` (
`col1` INT (11) DEFAULT NULL,
`col2` INT (11) DEFAULT NULL
)
SELECT 1 `col1`, 2 `col2`;
and should work with mysql_query
I have two mysql insert statements. The one with all the fields specified in insert statement works fine and insert record to testTable.(Even when http_referer is empty the insert statement insert records to table with referer field empty)
First Insert statement with all fields specified:
mysql_query("INSERT INTO testTable VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1','".$_SERVER['HTTP_REFERER']."')");
The problem is with second insert statement that doesn't insert any record to testTable!
Could you guys tell me why my second insert statement doesn't insert any record to testTable?
Second insert Statment:
mysql_query("INSERT INTO testTable VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1')");
Create Table:
CREATE TABLE IF NOT EXISTS `testTable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(32) DEFAULT NULL,
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`Title` varchar(32) NOT NULL,
`Ref` varchar(250) NULL default '',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1784 ;
Yes, by using a column list.
$sql = "INSERT INTO table (`ip`, `date`, `Title`) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW(), 'Page 1')";
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which.
You can choose to specify which columns you want to insert into in an insert statement.
$sql = "INSERT INTO testTable(ID, ip, date, Title)
VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1')";
Additionally, please don't use mysql functions as they are deprecated now. Use MySQLi, or PDO
You have to specify the fields with the second query. If you're not going to insert every column, in the order of the columns, then you have to specify the column names.
INSERT INTO table (column1, column2, columns3) VALUES ('$value1', '$value2', '$value3');
You can use a column list or SET syntax
Column list:
INSERT INTO table (column1, column2) VALUES ('$value1', '$value2');
SET syntax:
INSERT INTO table SET column1 = '$value1', column2 = '$value2';
In first query error not comes because you are specifying all column and fieleds.If any filed is auto increment or by default null you should mention all the column name along with values in insert query accepting null of auto increment field
this are demo with
All field value
insert into testtable values (1,"127.1.1.0",curdate(),"test 1","default");
Without Default value
insert into testtable (id,ip,date,title) values (1,"127.1.1.0",curdate(),"test 1");
without auto increment field
insert into testtable (ip,date,title) values ("127.1.1.0",curdate(),"test 1");