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.
Related
I have to use the $id variable as table name but it is not working.
$sql1="CREATE TABLE $id(
amt_to_be_paid INT(6),
no_of_days_req INT(2),
proposal TEXT NOT NULL,
channel_link VARCHAR(100) NOT NULL,
)";
Be sure that you have the full control on the $id variable and is not coming from user input.
You need to concatenate your $id variable to the query string, as following:
$sql1="CREATE TABLE " . $id . "(
amt_to_be_paid INT(6),
no_of_days_req INT(2),
proposal TEXT NOT NULL,
channel_link VARCHAR(100) NOT NULL,
)";
Take a look at this answer for a detailed review of how to achieve this : How to include a PHP variable inside a MySQL statement
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 try to update an existing table in mysql, but I get strange results, I explain my problem:
My table looks like this:
TABLE `myTable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`photoName` varchar(255) COLLATE latin1_general_ci NOT NULL,
`vote` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `photoName_2` (`photoName`),
)
and im trying to use saveVote.php that look like this:
$namePhoto = $_POST['name'];
$likePhoto = $_POST['like'];
mysql_connect("host","dbUser","psw");
mysql_select_db("db_is");
mysql_query("INSERT INTO `myTable` (`photoName`,`vote`) VALUES('$namePhoto','$likePhoto') ON DUPLICATE KEY UPDATE vote = vote + 1");
the 'vote' value is updated but every time when i call the "saveVote.php", for the first time he create an empty entry in my table with only the vote value and after, each time the "saveVote.php" is called
the vote value is updated for the right photoName but the vote value for the empty entry is also updated.
Why my request created this empty entry ?
Thanks for help.
It seems like your $namePhoto = $_POST['name']; is also returning a empty value. Try this:
if(!empty($_POST['name'])){
mysql_query("INSERT INTO `myTable` (`photoName`,`vote`) VALUES('$namePhoto','$likePhoto') ON DUPLICATE KEY UPDATE vote = vote + 1");
}
Keep in mind that this is just to test. This is not a fix. You need to figure out why you are sending a empty value.
I have looked at other posts and tried some of the suggestions but I still can't seem to populate a specific table in my database.
I will supply some blocks of my code to put things into perspective.
Here is my code for creating the table I want to populate with data:
CREATE TABLE `Devices` (
`dID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`deviceType` enum('BT','C1','AW') DEFAULT NULL COMMENT 'BT = Bluetooth, C1 = C1 Reader, AW = Acyclica Wifi',
`deviceName` varchar(255) NOT NULL DEFAULT '',
`deviceIP` varchar(15) NOT NULL DEFAULT '',
`devicePort1` int(4) NOT NULL,
`devicePort2` int(4) DEFAULT NULL,
`deviceRealLatitude` float(10,6) NOT NULL,
`deviceRealLongitude` float(10,6) NOT NULL,
`deviceVirtualLatitude` float(10,6) DEFAULT NULL,
`deviceVirtualLongitude` float(10,6) DEFAULT NULL,
`deviceChanged` tinyint(1) DEFAULT NULL,
`deviceStatus` tinyint(1) DEFAULT NULL,
`deviceLastSeen` timestamp NULL DEFAULT NULL,
`deviceBufferSize` int(4) DEFAULT NULL,
`deviceSoftwareVersion` varchar(20) DEFAULT NULL,
`deviceMacAddress` varchar(17) DEFAULT NULL,
`deviceTest` tinyint(1) DEFAULT NULL,
`deviceAPIKey` varchar(100) DEFAULT NULL COMMENT 'Only used with the Acyclia Scanners',
`deviceSerialID` int(6) DEFAULT NULL COMMENT 'Only used with the Acyclia Scanners',
PRIMARY KEY (`dID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
I have declared all the field variables i.e
$dID = 0;
.....
$deviceSerialID = 0;
I checked if each field is set i.e
isset($_POST['dID']) == 1 ? ($dID = ($_POST['dID'])) : null;
.....
isset($_POST['deviceSerialID']) == 1 ? ($deviceSerialID = ($_POST['deviceSerialID'])) : null;
Here is where I use INSERT INTO "table name" --> VALUES
$insert_query = "INSERT INTO Devices (`dID`, `deviceType`, `DeviceName`, `deviceIP`,
`devicePort1`, `devicePort2`, `deviceRealLatitude`, `deviceRealLongitude`,
`deviceVirtualLatitude`, `deviceVirtualLongitude`, `deviceChanged`, `deviceStatus`,
`deviceLastSeen`, `deviceBufferSize`, `deviceSoftwareVersion`, `deviceMacAddress`,
`deviceTest`, `deviceAPIKey`, `deviceSerialID`) VALUES ('".$dID."', '".$deviceType."',
'".$deviceName."', '".$deviceIP."', '".$devicePort1."', '".$devicePort2."',
'".$deviceRealLatitude."', '".$deviceRealLongitude."', '".$deviceVirtualLatitude."',
'".$deviceVirtualLongitude."', '".$deviceChanged."', '".$deviceStatus."',
'".$deviceLastSeen."', '".$deviceBufferSize."', '".$deviceSoftwareVersion."',
'".$deviceMacAddress."', '".$deviceTest."', '".$deviceAPIKey."',
'".$deviceSerialID."')";
mysqli_query($conn,$insert_query);
Now, in my html form, I only want to input data for some of the fields:
<fieldset>
<form name = "form1" id = "form1" action = "" method = "post">
Device ID: <input type="text" name="dID" > <br>
Device Type: <select name="deviceType">
<option value = "BT">BT</option>
<option value = "C1">C1</option>
<option value = "AW">AW</option>
</select> <br>
Device Name: <input type="text" name="deviceName" > <br>
Device IP: <input type="text" name="deviceIP" > <br>
Device Port 1: <input type="text" name="devicePort1"> <br>
Device Port 2: <input type="text" name="devicePort2"> <br>
<input type = "submit" name = "submit" value = "submit" />
</fieldset>
</form>
I get no errors when I enter my data and hit submit. I realize that some of the things I have done in the code are not necessary such as the tick marks. Its all been a matter of trying to see if it would fix my problem. Any suggestions as to what I can do please?
UPDATE 6/20/14
It seems that trouble lies in my CREATE TABLE syntax. When I replace type 'int' or 'float' with 'varchar', for the fields (dID is an exception), it updates the table. Anyone familiar with posting an 'int' or 'float' value?
UPDATE 6/20/14 A couple hours later...
Guys, it seems I have discovered the problem. It was a small technical issue and I complicated the code to drown in further error.
The idea follows this:
I do not need to worry about a field being set at this point, as many fields will remain null. I only need to fill a few out using this method for each field:
i.e
$deviceType = $_POST['deviceType'];
Also, the using an 'int' or 'float' requires a difference in how to implement the INSERT INTO ... VALUES clause. If leaving it null (which I am for now), I cannot do this:
$insert_query1 = "INSERT INTO Devices (deviceChanged) VALUES ('$deviceChanged');
This iteration was preventing the table from being filled with its appropriate values.
Instead, fill it with null:
$insert_query1 = "INSERT INTO Devices (deviceChanged) VALUES (NULL);
PHP now inserts data into MySQL. Thanks for the help!
isset return boolean value (true/false) not integer or something else (http://www.php.net//manual/en/function.isset.php)
And another mistake is about how you use ternary comparision. See more about that here: http://davidwalsh.name/php-shorthand-if-else-ternary-operators
So instead of:
isset($_POST['deviceName']) == 1 ? ($deviceName = ($_POST['deviceName'])) : null;
you should write
$deviceName = isset($_POST['deviceName']) ? $_POST['deviceName'] : null;
Also please consider using some sort of loop to assign these variables (if they are at all needed) and not duplicate your code in huge amounts.
You are trying to insert a string in a place of a float.
You should remove the ticks from the non varchar columents. example devicePort1 is declared and int but the insert statement is sending a value with a tick like this , '".$devicePort1."', instead of this, because MySQL expects an int u should send the , ".$devicePort1.", , i.e with out the ticks.
Also because ID is AUTO_INCREMENT You should not to try to set value to it. To check if your statement is correct echo $query , then try to execute that from MySQL console or PHPMyAdmin.
A good practice is to use prepared statements or PDO. check this PHP: PDO - Manual or Prepared Statements Manual. Those links are from Php.net and they contain a very good explanation with examples;
I want to be able to create dynamic tables, for custom user surveys... like survey monkey... how would I go about create something like that?
Because I want to give the ability to the user to create the survey, with different amount of text fields, and different a option fields... I would need to create a custom table for each survey.
Would something like this be possible?
<?php
$table_name = 'survey_'.$_POST['surveyid'];
$query = 'CREATE TABLE ? (
`responseid` INT NOT NULL AUTO_INCREMENT,
`textarea1` TEXT NULL,
`textarea2` TEXT NULL,
`textarea3` VARCHAR(255) NULL,
`drop_down1` VARCHAR(255) NULL,
`drop_down2` VARCHAR(255) NULL,
`bool1` BIT NULL,
`bool2` BIT NULL,
PRIMARY KEY (`responseid`))';
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('s', $table_name);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare");
?>
The above example comes back with "Failed to prepare", because I don't think I can prepare a table name... is there another work around using mysqli?
if(ctype_digit($_POST['surveyid']) && $_POST['surveyid']>0){
$table_name = 'survey_'.$_POST['surveyid'];
$query = 'CREATE TABLE '.$table_name.' (
`responseid` INT NOT NULL AUTO_INCREMENT,
`textarea1` TEXT NULL,
`textarea2` TEXT NULL,
`textarea3` VARCHAR(255) NULL,
`drop_down1` VARCHAR(255) NULL,
`drop_down2` VARCHAR(255) NULL,
`bool1` BIT NULL,
`bool2` BIT NULL,
PRIMARY KEY (`responseid`))';
I know I can just try to sanitize the $_POST['surveyid'] (like I did above) but I prefer to prepare it if possible.
$table_name = 'survey_'.$_POST['surveyid'];
Do not do the above. It is easy for a hacker to exploit your site if you include $_GET or $_POST data directly in any SQL string.
But you can't use parameters for a table name. A parameter takes the place of a single scalar value only. You can prepare CREATE TABLE but you can't use parameters for identifiers (e.g. table names).
The best practice is to make sure your table name conforms to a rule, for example only the leading portion of a string of numeric digits, up to the maximum length of a MySQL table name:
$table_name = 'survey_' . strspn(trim($_POST['surveyid']), '0123456789', 0, 56);
If you have other rules for a surveyid, then you could use preg_replace():
$table_name = 'survey_' . preg_replace('^(\w+)', '$1', trim($_POST['surveyid']));
It is not possible to prepare a data definition language statement like "CREATE TABLE". I can't find the reference in the MySQL docs that explains this, but I did find a good explanation on the PHP documentation site.