i want to create a table in the database using php (mysql_querry)
Table is having 'n' number of attributes.
out of n, n-2 attribute names are available in the array.
I can't explain where i am getting the array but it looks like this-
http://i.stack.imgur.com/tH98f.png
Here is the code for generating String to execute in mysql_querry.
$str="CREATE TABLE $register_name(id int NOT NULL AUTO_INCREMENT, date DATE, ";
$j=0;
while($j<$i)
{
$str=$str.$roll_no[$j]." int(100), ";
$j++;
}
$str=$str."PRIMARY KEY(id))";
require('blogic.php');
$obj = new blogic();
$createtable=$obj->create($str);
When i echo the $str, I get this:
CREATE TABLE $register_name(id int NOT NULL AUTO_INCREMENT, date DATE, 913310128 int(100), 0913310129 int(100), PRIMARY KEY(id))
However, it is giving error like this
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 '913310128 int(100), 0913310129 int(100), PRIMARY KEY(id))' at
line 1
I don't understand the problem. when i don't use roll_no array, it works fine..
Please let me know what is the problem in this.
From the docs:
"Identifiers may begin with a digit but unless quoted may not consist solely of digits."
So, you could just quote the name:
$str=$str."`".$roll_no[$j]."` int(100), ";
Or, prefix it with a letter:
$str=$str."c".$roll_no[$j]." int(100), ";
Related
so, i'm trying to show a certain value in a table row, if the value recieved by post is null.
So far i've got this as my small database (it's in spanish):
DROP DATABASE IF EXISTS fantasmas;
CREATE DATABASE fantasmas;
USE fantasmas;
CREATE TABLE tipos(
ID tinyint(2) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
TIPO VARCHAR(45) UNIQUE
);
CREATE TABLE datos(
ID tinyint(2) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
NOMBRE VARCHAR(50) NOT NULL,
ARCHIVO VARCHAR(30),
AVISTAMIENTO VARCHAR(50) NOT NULL,
LOCALIDAD VARCHAR(50) NOT NULL,
INFO VARCHAR(200),
FKTIPOS TINYINT(2) UNSIGNED,
FOREIGN KEY (FKTIPOS) REFERENCES tipos(ID)
);
INSERT INTO tipos (TIPO) VALUES('Vapor'), ('Forma Animal'), ('Forma Humanoide'), ('Dios/Semidios'),('No Catalogado');
Those inserted values into "tipos" are then showed in options like this:
<select name="tipos">
<option value="sintipo">---------</option>
<?php
while( $row = mysqli_fetch_assoc($rta)):
$tipo = $row['TIPO'];
echo '<option value="'.$row['ID'].'">'.$tipo.'</option>';
endwhile;
?>
</select>
After, when the form is sent, the inset to the table, looks like this, it assigns null value if someone select the "------" option:
$query = "INSERT INTO datos SET NOMBRE='$nombre', AVISTAMIENTO='$lugar', LOCALIDAD='$localidad', INFO='$info', ARCHIVO='$ruta', FKTIPOS = NULLIF('$tipo','sintipo')";
All the data filled in the form, is then showed in a different row of a table.
What I need now, is that, if someone selects the "------" option, the value shown in screen is "No catalogado"
So far I have not been able to do it.
Can anyone help me?
Before the insert happens you can do a null check on the PHP side. Or... you can just use SQL's built in ISNULL()
You can also use CASE statements in SQL to accomplish this behavior across multiple values.
I know this isn't the most lengthy answer, but it should work.
Is this what your asking for?
$query = "INSERT INTO datos SET NOMBRE='$nombre', AVISTAMIENTO='$lugar', LOCALIDAD='$localidad', INFO='$info', ARCHIVO='$ruta', FKTIPOS = " . ($tipo == 'sintipo' ? 'NULL' : "'$tipo'");
Be aware that you have very dirty code, you don't even filter and escape income values, as I guess. Try to google php mysql escape values.
I have created a database composed of three tables. This is my query in creating my tables with Foreign Key.
CREATE TABLE reporter
(
reporterid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(1000) NOT NULL,
lastname VARCHAR(100) NOT NULL,
PRIMARY KEY (reporterid)
);
CREATE TABLE flood
(
floodid INT NOT NULL AUTO_INCREMENT,
address VARCHAR(500) NOT NULL,
description VARCHAR(1000) NOT NULL,
dateofflood DATE NOT NULL,
timeofflood INT NOT NULL,
PRIMARY KEY (floodid)
);
CREATE TABLE reports
(
reportid INT NOT NULL AUTO_INCREMENT,
timereport NODATATYPE NOT NULL,
datereport DATE NOT NULL,
rid INT NOT NULL,
fid INT NOT NULL,
PRIMARY KEY (reportid),
FOREIGN KEY (rid) REFERENCES reporter(reporterid),
FOREIGN KEY (fid) REFERENCES flood(floodid)
);
I created a system in order for me to add records/row on my database through PHP. This is my code:
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("flooddatabase")or die("Connection Failed");
$description = $_POST['description'];
$address = $_POST['address']; // Make sure to clean the
$dateofflood=$_POST['dateofflood'];
$timeofflood=$_POST['timeofflood'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$dateofreport=$_POST['dateofreport'];
$timeofreport=$_POST['timeofreport'];
$query = "INSERT into flood(address,description,dateofflood,timeofflood) values ('$address','$description','$dateofflood','$timeofflood')";
$query2 = "INSERT into reporter(firstname,lastname) values ('$firstname','$lastname')";
$query3 = "INSERT into reports(dateofreport,timeofreport) values ('$dateofreport','$timeofreport')";
if(mysql_query($query))
if(mysql_query($query2))
if(mysql_query($query3))
{
echo "";
} else
{
echo "fail";
}
?>
The result that I am getting is fine. It's just that, in my REPORTS table, there is no foreign key that is being generated. For example I input something on my reporter table and flood table, the foreign key 'rid' and 'fid' has no values that references to both tables. Need help thank you.
Get the just inserted Primary key value from flood table insert
query. And store it to a variable say $f_id;
Get the just inserted primary key value from reporter table insert
query and store it to a variable say $r_id;
Now Make your last insert statement like below:
"INSERT into reports(dateofreport,timeofreport,rid,fid) values ('$dateofreport','$timeofreport',$r_id,$f_id)";
I am not giving you a direct copy paste solution.
If you need to know how to get the last inserted id by executing an insert query then look at this link
there is no foreign key that is being generated
I'm not entirely sure what you even mean by that. Foreign keys aren't "generated". Primary keys can be, which you do:
reporterid INT NOT NULL AUTO_INCREMENT
(as well as for your other two tables)
the foreign key 'rid' and 'fid' has no values
Well, look at your query:
INSERT into reports(dateofreport,timeofreport) values ...
Where do you insert values for rid and fid? I'm actually pretty surprised this query works at all, since those columns don't allow NULL values:
rid INT NOT NULL,
fid INT NOT NULL,
(Though your column names also don't line up, so I find it likely that the code you're showing isn't actually the code you're using...) That point aside however, the fact still remains that if you want a value in those fields then you have to put a value in those fields:
INSERT into reports(dateofreport,timeofreport,rid,fid) values ...
After each query, you can get the last generated identifier from mysql_insert_id():
$last_id = mysql_insert_id();
Use that to then populate the values being inserted as foreign keys in subsequent queries.
Also worth noting, the mysql_* libraries are long since deprecated and have been replaced with mysqli_ and other libraries such as PDO. I highly recommend you upgrade to a current technology, since what you're using isn't supported by any vendor.
Additionally, and this is very important, your code is wide open to SQL injection attacks. This basically means that you execute any code your users send you. You should treat user input as values, not as executable code. This is a good place to start reading on the subject, as is this.
I'm trying to create a table if it does not already exist in my database. For this I'm running this test which is working as intended:
$conn = mysql_connect("localhost", "twa222", "twa222bg");
mysql_select_db("airline222", $conn) or die ("Database not found " . mysql_error() );
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
However my problem comes when I try to create the table itself, which is giving me the following error:
Problem with query: 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 ''passenger' SMALLINT NOT NULL, 'booking' CHAR(6), 'seat' VARCHAR(3))' at line 2
This is the code that is attempting to generate the table
if(!$val)
{
$sql = "CREATE TABLE ".$FLIGHTID." (
passenger SMALLINT NOT NULL PRIMARY KEY,
booking CHAR(6), seat VARCHAR(3) )";
$rs = mysql_query($sql) or die ("Problem with query" . mysql_error());
}
mysql_close($conn);
I originally thought it was the ".$FLIGHTID." that was causing the problem but when I changed that to simply be ABC I still got the same error.
Can anyone see where I am going wrong?
EDIT:
My SQL output when using ABC is:
CREATE TABLE ABC ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
Without using ABC it is:
CREATE TABLE ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
You use single quotes arround column names what is not allowed. Single qoutes indicates that the value inside is a litaral:
Change:
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
to:
$val = mysql_query("SELECT 1 from $FLIGHTID");
Use mysqli_*or PDOinstead of deprecated mysql_* API.
I am trying to make an SQL query that :
IF the $post_id exists then it updates the records,
IF NOT then then it creates the record
Here is my code
$vote_new_total = $vote_total + $vote;
$vote_count = $vote_count + 1;
$query = " INSERT INTO cute_review_vote (vote_total, vote_count)
VALUES ('$vote_new_total', '$vote_count')
ON DUPLICATE KEY UPDATE vote_total = $vote_new_total, vote_count = $vote_count
WHERE post_id = $post_id";
mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
However, I keep getting the following error:
Notice: 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 'WHERE post_id = 214748364' at line 4 in in C:\xampp\htdocs\xbm-vote\do_vote.php on line 68
Is this an issue with my syntax or am I missing something more obvious than that?
Any help/advice would be greatly appreciated. Thanks.
There is no where with ON DUPLICATE statement. Always check syntax: http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Also, that is not a secure query. Turn that into a prepared statement.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
EDIT: Updating answer since OP didn't understand usage of ON DUPLICATE statement:
ON DUPLICATE will consider that you're trying to insert a KEY value.
Consider the example table:
CREATE TABLE `user` (
`email` varchar(50) NOT NULL,
`name` varchar(20) NOT NULL,
`is_active` tinyint(4) NOT NULL,
`datecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`email`)
);
And the query:
INSERT INTO user (email, name, is_active) VALUES ("user#user.com", "User", 1)
ON DUPLICATE KEY UPDATE name = "User Edited", is_active = 0
Since we're setting PRIMARY KEY as email, and the insert statement is inserting a key, then, at the second time you run the query, ON DUPLICATE would run once a email is already on the table, because it is the KEY and you are trying to insert it again, but you defined a ON DUPLICATE KEY ....
If a table runs with a AUTO_INCREMENT column, is most likely you have to SELECT post_id applying some filter with WHERE statement.
Ok, I found my problem.
INSERT INTO cute_review_vote (post_id, vote_total, vote_count)
VALUES ('$post_id', '$vote_new_total', '$vote_count')
ON DUPLICATE KEY UPDATE vote_total = $vote_new_total, vote_count = $vote_count
I realized, thanks to Fabiano, that the WHERE clause is not required.
WHERE post_id = $post_id"
Is simply replaced by defining the database entry within the INSERT INTO command.
php
$dnumber = '9515551212';
$device_id = 'f3847010927038970110923';
device is a text field
phnum (I have used bigint, text, varchar) all give the same result.
mysql_query("INSERT INTO devices(device, phnum) VALUES('$device_id', '$dnumber')");
the above query is TRUE but the value in phnum will be empty.
mysql_query("INSERT INTO devices(device, phnum) VALUES('$device_id', $dnumber)");
the above query is FALSE, but it still inserts the record perfectly! I also get error 1064 near ")" (I removed the quotes from $dnumber)
So why is the first saying it succeeded but didnt put anything there while second says it fails but it inserted it as I wanted it to?
I think, there's something with incoming data. SQL works well.
I tried that query from php:
$sql = "INSERT INTO test(device_id, phnum) VALUES('$device_id', '$dnumber')";
$res = mysql_query($sql);
For the table with the following structure:
CREATE TABLE `test` (
`phnum` int(30) unsigned NOT NULL AUTO_INCREMENT,
`device_id` varchar(256) NOT NULL DEFAULT '',
PRIMARY KEY (`phnum`)
) ENGINE=InnoDB AUTO_INCREMENT=4294967295 DEFAULT CHARSET=utf8;
It worked well without any warnings. From SQL client - the same, works well.