Struggling with geo data/polygons in MySQL database - php

I have a table which contains an field zoneShape of the type Polygon.
When inserting some geometry in this field, in phpmyadmin it says: affected 1 row. The row is added, but the geometry field says it's size is 0B.
This is the Insertion code:
SET #g = 'POLYGON(50.866753 5.686455, 50.859819 5.708942, 50.851475 5.722675, 50.841611 5.720615, 50.834023 5.708427, 50.840744 5.689373, 50.858735 5.673923, 50.866753 5.686455)';
INSERT INTO zone SET zoneShape = PolygonFromText(#g)
As you can see; the first and last point are the same, so the polygon is closed.
Can anyone help me with adding this polygon to the database?
Thanx

It turns out that you need to add some extra brackets around the Points; because the standard uses an outside and inside line aka holes or islands.
So:
SET #g = 'POLYGON((50.866753 5.686455, 50.859819 5.708942, 50.851475 5.722675, 50.841611 5.720615, 50.834023 5.708427, 50.840744 5.689373, 50.858735 5.673923, 50.866753 5.686455))';
^ outside ^

INSERT INTO zone SET zoneShape = PolygonFromText(#g) doesn't look like a valid INSERT statement to me. Did you mean INSERT INTO zone (zoneShape) VALUES (PolygonFromText(#g));?

Related

How to add a possble value to a MySQL SET type in php, without know the current values

Hi everybody and sorry for my english.
I have the column "example" that is a SET type.
I have to make a php page where you can add values to that column.
First of all I need to know what is just in "example", to prevent the adding of an existing value by a control. Second of all I need to add the new value.
Here's what I had thinked to do.
//I just made the connection to the db in PDO or MySQLi
$newValue=$_POST['value']; //I take the value to add in the possible values from a form
//Now I have to "extract" all the possible values. Can't think how.
//I think I can store the values into an array
$result=$sql->fetch(); //$sql is the query to extract all the possible values from "example"
//So now i can do a control with a foreach
foreach($result as $control){
if ($newValue == $control){
//error message, break the foreach loop
}
}
//Now, if the code arrives here there isn't erros, so the "$newValue" is different from any other values stored in "example", so I need to add it as a possible value
$sql=$conn->query("ALTER TABLE 'TableName' CHANGE 'example' 'example' SET('$result', '$newValue')"); //<- where $result is the all existing possible values of "example"
In PDO or MySQLi, it's indifferent
Thanks for the help
We can get the column definition with a query from information_schema.columns
Assuming the table is in the current database (and assuming we are cognizant of lower_case_table_names setting in choosing to use mixed case for table names)
SELECT c.column_type
FROM information_schema.columns c
WHERE c.table_schema = DATABASE()
WHERE c.table_name = 'TableName'
AND c.column_name = 'example'
Beware of the limit on the number of elements allowed in a SET definition.
Remove the closing paren from the end, and append ',newval').
Personally, I don't much care for the idea of running an ALTER TABLE as part of the application code. Doing that is going to do an implicit commit in a transaction, and also require an exclusive table / metadata lock while the operation is performed.
If you need a SET type - you should know what values you add. Otherwise, simply use VARCHAR type.

php mysqli syntax for mixing variable with text in a field

hi and thank you in advance for any help you can give!
i'm iffy on syntax with variables in queries.
i have a database table with a column called 'iltr' and a column called 'refline'.
the 'refline' column is filled with text data like this: '1LINE1' '1LINE2' '1LINE3' '2LINE1' '2LINE2' '2LINE3' etc etc etc.
i want to use a variable that relates to the first digit of the data in the 'refline' column to update another column.
in the example below i'm trying to set 'iltr'= 'Y' where 'refline' is '2LINE3' by using a variable for the "2" digit in '2LINE3' instead of the "2" digit itself, and i don't even know if this kinda thing can be done.
this code syntax below does not work specifically in the WHERE segment where i try to mix the variable with the actual text in the column:
$slot=2;
$sql = "UPDATE overall SET iltr='Y' WHERE refline='$slotLINE3'";
i hope you can forgive my inexperience. thanks again and have an awesome day!
Your code is trying to substitute a variable named $slotLINE3. You need to use a delimiter to end the variable name.
$sql = "UPDATE overall SET iltr='Y' WHERE refline='{$slot}LINE3'";

Missing leading Zero's when inserting Strings

I actually get very mad about PHP and SQLite3 and the way some of my strings behave there.
I try to save opening hours but in strings instead of numeric to prevent problem with leading zeros (and still have it now haha... -.-).
Hours and minutes have their own column but when I insert '0x' the zero is gone and whatever x is, is left in the database. :/
Im sure im just missing some little damn part somewhere...
I already checked the INSERT-statement but found nothing at all.
Example for an insert string:
INSERT INTO opening INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('Montag', 'Freitag', '00', '00', '01', '00')
But the output is:
11|Montag|Freitag|0|0|1|0
Part of the Code:
class Database_Opening_Hours extends SQLite3{
function __construct() {
if(!file_exists("../../data/opening_hours/opening_hours.sqlite")){
$this->open("../../data/opening_hours/opening_hours.sqlite");
$this->exec('CREATE TABLE opening (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, start_day STRING, end_day STRING, start_hour STRING, start_minute STRING, end_hour STRING, end_minute STRING)');
}
else{
$this->open("../../data/opening_hours/opening_hours.sqlite");
}
}
}
$db = new Database_Opening_Hours();
$insert = "INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('".htmlspecialchars($_GET["start_day"])."','".htmlspecialchars($_GET["end_day"])."','".$start_hour."','".$start_minute."','".$end_hour."','".$end_minute."')";
if($db->exec($insert)){
$db->close();
unset($db);
echo "Insert erfolgreich";
}else{
$db->close();
unset($db);
echo "Nicht wirklich...";
}
Fairly sure that the type of your columns is set to an integer (or any other number type) instead of TEXT.
Make sure to double check the column data type and actually dump the table for us to check if it's really set to TEXT.
This is caused by SQLite using dynamic typing. From the FAQ:
This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Data of any type can (usually) be inserted into any column. You can put arbitrary length strings into integer columns, floating point numbers in boolean columns, or dates in character columns. The datatype you assign to a column in the CREATE TABLE command does not restrict what data can be put into that column. Every column is able to hold an arbitrary length string.
And from the linked page (emphasis mine):
In order to maximize compatibility between SQLite and other database engines, SQLite supports the concept of "type affinity" on columns. The type affinity of a column is the recommended type for data stored in that column. The important idea here is that the type is recommended, not required. Any column can still store any type of data. It is just that some columns, given the choice, will prefer to use one storage class over another. The preferred storage class for a column is called its "affinity".
So SQLite is dynamically casting your values to integer.
I would suggest combining start_hour and start_minute into start_time (the same for the end_ fields) and storing the value in the format 00:00.
SQLite will store this 'as-is' but is smart enough to recognise a time value and allow you to perform date/time operations:
select time(start_time, '+1 hour') from opening
I had this problem with C/C++ because I did not quote the strings:
insert into test values('aa', 'bb');
use varchar instead of string, I had the same problem then I used varchar(length) and it worked fine

Search value of a field using substring

I'm working on a project using the pages in php / mysql and html; I have a table that contains the data for calls made from a PBX and save the number called, the source, date, time, etc ... what I want to do is to search within this table all the phone numbers that have the first 4 digits equal to those that pass through the query, only that i have no idea how to pull off only the 4-digit or at least how to make a control character by character of the value contained in the field. I tell you now that the field is a varchar. Thank you in advance :)
To do that in MySQL query, either
SELECT *
FROM <tablename>
WHERE LEFT(<column>, 4) = "<4 digits>"
or
SELECT *
FROM <tablename>
WHERE <column> LIKE "<4 digits>%"
or in the PHP side :
if (strpos($column,'<4 digit>') !== false) {
echo 'true';
}
Use this, to get substring
SELECT aut_name,
RIGHT(aut_name,7)
FROM author
WHERE country='UK';
See more at: http://www.w3resource.com/mysql/string-functions/mysql-right-function.php#sthash.xKNwZeki.dpuf
I suggest this solution:
$variableWhereYoustoreTheFourDigits="1234"; //Use whatever you have in your code to set the value.
$result =$mysqli->query("SELECT number FROM yourtable where number LIKE \"$variableWhereYoustoreTheFourDigits%\");

MySQL returning an empty result set

I tried doing this in PHP but I got 0 rows returned all the time. Then after some time searching around on StackOverflow, I saw a tip to try doing it in SQL first to see if the results are returned properly.
I tried to do it in SQL and it's returning an empty result set all the time, even tho the values are there.
SQL
SELECT * FROM `serials_table` WHERE `ser_key`='ABCD-EFGH-IJKL-MNOP'
PHP
$result = $link->query("SELECT * FROM serials_table WHERE ser_key='$key'");
Both are returning null value.
ser_key column is set to text type, coallition: utf8_unicode_ci, Null: No, Default: None
The serial key entry is in there and the column 'ser_key' exists as well as the table 'serials_table'. Also I directly copy-pasted the serial key from the table and placed it into the query to avoid any typos.
Did I make some errors with the table structure or something?
I have no idea what to do here, any help would be appreciated.
When this works
SELECT * FROM serials_table WHERE ser_key like '%ABCD-EFGH-IJKL-MNOP%'
Then you have leading or trailing spaces in your data.
To revert that update your existing table data like this
update serials_table
set ser_key = trim(ser_key)
After that check where you insert or update the ser_key. In that code segment check if you put only trimmed data in there.
Try
SELECT * FROM `serials_table` WHERE TRIM(`ser_key`)='ABCD-EFGH-IJKL-MNOP'
Remove white spaces
UPDATE `serials_table` set `ser_key`= TRIM(`ser_key`);

Categories