I have created a tabe with values using this command :
CREATE TABLE `news` (
`id` int(11) NOT NULL auto_increment,
`title` text NOT NULL,
`content` text NOT NULL,
`price` text NOT NULL,
`link` text NOT NULL,
`ppcode` text NOT NULL,
`type` text NOT NULL,
PRIMARY KEY (`id`)
)
And when i use this php codes i cant update any value of the columns :
if (isset($_POST['edit'])){
$delsql = "UPDATE news SET title='$newsubject',content='$newdisc',link='$newlink',
price='$newprice',ppcode='$newppcode' WHERE id = '$id'";
$result = mysql_query($delsql) or die(mysql_error());
echo 'OK';
}
Note : the version of MySQL is 3.5.2.2 and the version of PHP is 5.3
Use mysqli_* functions or PDO!!!!
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$stmt = $conn->prepare("UPDATE news SET title=?,content=?,link=?,price=?,ppcode=? WHERE id =?");
$stmt->bind_param('sssdii',$newsubject,$newdisc,$newlink,$newprice,$newppcode,$id);
// i corresponding variable has type integer
// d corresponding variable has type double
// s corresponding variable has type string
// b corresponding variable is a blob and will be sent in packets
$stmt->execute();
$row_count= $stmt->affected_rows;
$stmt->close();
$conn->close();
Beside all the suggestion on the comments
You have
WHERE id = '$id'";
but id is integer not text
CREATE TABLE `news` (
`id` int(11) NOT NULL auto_increment,
In image of phpmyadmin that you provided in comments you can see that A_I (auto_increment) is not active. Also primary key is not set. Set A_I to true for id and set it as primary key (under Index) in phpmyadmin. Then test it with your code.
Of course first insert new data which will have auto incremented id's.
Related
So I'm trying to create a table and then insert multiple values into it, like so:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "someDbName";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE IF NOT EXISTS someTableName(
someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
someVar1 VARCHAR(30) NOT NULL,
someVar2 INT NOT NULL);
INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ('someString1', someInteger1),
('someString2',someInteger2);";
Where the someInteger bits are, of course, integers. And then:
$sql = mysqli_real_escape_string($conn, $sql);
if (mysqli_multi_query($conn, $sql)) {
dtconsole("Tables populated successfully");
} else {
dtconsole("Error creating table: " . mysqli_error($conn));
}
With the dtconsole function there just to output to console to help me debug.
function dtconsole($data){
$output=$data;
if(is_array($output)){
$output=implode(',',$output);
}
echo '<script>console.log("'.$output.'");</script>';
}
Every time I try to run this, it returns the following error:
Error creating table: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near '
someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, ' at line 1
And I can't for the life of me see what I'm doing wrong.
Your problem is that you are calling mysqli_real_escape_string on your entire query, instead of just the values you are inserting. As a result it is converting the CR-LF in your $sql string into \r\n, which the MySQL parser cannot interpret. You should be doing something like this:
$someString1 = mysqli_real_escape_string($conn, 'someString1');
$someString2 = mysqli_real_escape_string($conn, 'someString2');
$sql = "CREATE TABLE IF NOT EXISTS someTableName(
someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
someVar1 VARCHAR(30) NOT NULL,
someVar2 INT NOT NULL);
INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ($someString1, someInteger1),
($someString2,someInteger2);";
if (mysqli_multi_query($conn, $sql)) {
...
I want to create a table with variables passed into my php file. However, the SQL does not work when I pass in '12345' and works when I pass in 'a12345' instead.
This is my error that is given.
Error creating the table
query was
CREATE TABLE 123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50)
NOT NULL, gasquality VARCHAR(50) NOT NULL, timestamp DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP)
mysqlerror: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
'123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50) NOT NULL,
gasq' at line 1
Creating database failed!
and my function that creates the table
function CreateTableNode(&$formvars)
{
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." (".
" humidity VARCHAR(50) NOT NULL, ".
" temperature VARCHAR(50) NOT NULL, ".
" gasquality VARCHAR(50) NOT NULL, ".
" timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
if(!mysqli_query($this->connection,$qry))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}
I want to be able to create tables with numeric names like '12345' or '154124' for other purposes. Thanks alot!
My suggestion:
Provide a prefix to the table you created.
Moreover, I couldn't
see the primary key in your table. However, it is not necessary to
have it but if your table design doesn't have a primary key, you need
to rethink your design. It plays a vital role to join tables.
Your code can be rewritten as:
function CreateTableNode (&$formvars) {
$host = 'localhost';
$database = 'test';
$dbuser = 'root';
$dbpass = '';
try {
$pdo = new PDO('mysql:host=localhost; dbname=test', $dbuser, $dbpass);
} catch (PDOException $e) {
print "ERROR! : " . $e->getMessage() . "<br/>";
die();
}
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." ("."
`id` INT NOT NULL AUTO_INCREMENT ,
`humidity` VARCHAR(50) NOT NULL ,
`temperature` VARCHAR(50) NOT NULL ,
`gasquality` VARCHAR(50) NOT NULL ,
`timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)";
$stmt = $pdo->prepare($qry);
$stmt->execute();
$pdo = null;
return true;
}
You just need to wrap some elements in the query with quotes as the duplicated thread mentioned by underscore_d says:
$qry = "CREATE TABLE '$serialno' (
'humidity' VARCHAR(50) NOT NULL,
'temperature' VARCHAR(50) NOT NULL,
'gasquality' VARCHAR(50) NOT NULL,
'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
This will fix your syntax errror in the query.
Marking to close the question as duplicated
The name of the entity was expected. (near "123456" at position 13)
Try adding a prefix to the table name as such
"t_12345"
CREATE TABLE t_12345
MySql does not allow numeric values as table name.
MySQL doesn't allow the creation of tables with names made solely of digits unless the name is quotes. See here
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Try quoting the name with backticks (`) or prefix the table name.
The error says "Creating database failed!".
So I assume you haven't selected the database in the connection query. You should do that or select it with "use mydatabase;" first. Of course, you may need to create the database first.
With PDO it would look like:
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Please see dbname=myDB which preselects the right db for you.
Reference: https://www.w3schools.com/php/php_mysql_connect.asp
Using mysql functions, you can use:
mysql_select_db($dbname)
Reference: http://php.net/manual/en/function.mysql-select-db.php
I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: 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 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..
So I have this script just to create a table in my database. I've copied it over from an old script I did that is working right now. How come this one is not working? Anyone?
The error I am getting is "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 "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"
<?php
include("server_connect.php");
mysql_select_db("assignment5");
$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";
$results = mysql_query($create) or die (mysql_error());
echo "The tables have been created";
?>
Remove all = as already suggested:
$create = "CREATE TABLE tbltable (
column_one varchar (20) NOT NULL,
column_two int NOT NULL auto_increment PRIMARY KEY,
column_three int NOT NULL,
column_four varchar (15) NOT NULL,
column_five year
)";
Each and every table should have a primary key and you must specify AUTO_INCREMENT column as PRIMARY KEY. In this case, the AUTO_INCREMENT column is column_two and I've set that as the PRIMARY KEY.
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
(PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The solution is to assign all the privileges to the BD user, like this:
GRANT ALL PRIVILEGES ON *. * TO 'user_name' # 'localhost';
I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !