PHP/PostgreSQL database writing issue - php

I'm having problems writing data from a form to multiple datatables on my PostgreSQL database.
Here is my data model
CREATE TABLE institutions(i_id PK, name text, memberofstaff REFERENCES staff u_id);
CREATE TABLE staff(u_id PK, username text, password text, institution REFERENCES institutions i_id);
So its a 1:1 relationship. These tables have been set up fine. It's the PHP script I'm having difficult with. I'm using CTE-datamodifying or at least trying to but I keep receiving errors on submit.
The PHP:
$conn = pg_connect('database information filled out in code');
$result = pg_query("WITH x AS (
INSERT INTO staff(username, password, institution)
VALUES('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING u_id, i_id)
INSERT INTO institutions (i_id, name, memberofstaff)
SELECT x.i_id, x.u_id, '$institution'
FROM x");
pg_close($conn);
So that's the code and the error I get is:
Warning: pg_query() [function.pg-query]: Query failed: ERROR: relation "institutions_i_id_seq" does not exist LINE 3: VALUES('AberLibrary01', '', nextval('institutions_i_id_se... ^ in DIRECTORY LISTING(I replaced this) on line 22
Anyone got any ideas?

Did you actually create the table with the column types of institutions.i_id and staff.u_id set to serial? Or create the sequence manually?
If the former, you don't need to explicitly use nextval anyway. If the latter, double-check the sequence name.

This would ideally be a comment, but I think it might have something to do with:
$'password' which should be '$password' on the fourth line of that example.

Related

PHP - Left join from two tables in different databases with different credentials using PDO

Please note: While my original issue was not possible to be solved in the way I expected, #Bamar solution marked in this post is an alternative that reaches the same goal and works perfectly. What I proposed in this post to be done doesn't seem to be viable if the databases are located in different hosts.
I've been searching for a while and I seem to be unable to solve my issue.
THE DATA I HAVE
My service provider is 1&1. In the current contract I have with them I could create up to 100 databases with a maximun size of 2GB each.
Each database that is created, is assingned a random hostname, port and username (the only item which I can choose is the password).
I've got two different databases, lets call them DB_1 and DB_2.
In the DB_1 I've got a table called T_USERS which fields of interest for this particular problem are:
ID: The ID of the record.
userName: The user name registered on the database.
In the DB_2 I've got a table called T_SCORES which fields of interest for this particular problem are:
ID_User: it's a foregin key that refers to the ID of a particular user in DB_1.T_USERS
score: a numeric value that indicates the score of that user.
It is important to take into account that to access both databases each of them needs different credentials!
WHAT I WANT TO ACHIEVE
What I want to achieve seems simple at a first glance but I was unable to find any documentation or solution online on how to do this using PHP and PDO.
I just want to perform a join with DB_2.ID_USER and DB_1.ID
My final result should look something like this:
DB_1.userName
DB_2.score
Alex
237
Peter
120
Mark
400
...
...
WHERE I'M CURRENTLY STUCK
This is what I've currently tried.
First of all I perform the connection to my databases as follows (I normally use a try/catch when connecting to a DB but I will omit it here):
//Connection to the DB1
$db1_hostName = "hostnameofDB1";//The host name of the database 1
$db1_name = "db1";//The name of the database 1
$db1_userName = "user1";//The username in the database 1
$db1_password = "pw1";//The password for the database 1
$pdo_db1Handle = new PDO("mysql:host=$db1_hostName; dbname=$db1_name;", $db1_userName, $db1_password);
$pdo_db1Handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Connection to the DB2
$db2_hostName = "hostnameofDB2";//The host name of the database 2
$db2_name = "db2";//The name of the database 2
$db2_userName = "user2";//The username in the database 2
$db2_password = "pw2";//The password for the database 2
$pdo_db2Handle = new PDO("mysql:host=$db2_hostName; dbname=$db2_name;", $db2_userName, $db2_password);
$pdo_db2Handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So basically up to this point what I've done is very simple, create a pdo_db1Handle and pdo_db2Handle. Now to the tricky part...
If I now want to perform a join my SQL syntax should be something like this:
SELECT DB_1.T_USERS.userName, DB_2.T_SCORES.score
FROM DB_2.T_SCORES
LEFT JOIN DB_1.T_USERS
ON (DB_2.T_SCORES.ID_User=DB_1.T_USERS.ID)
ORDER BY DB_2.T_SCORES.score ASC 'The ordering is optional, I'm interested in the join part first
But as far as I'm aware and with all the information I was able to find, you execute the SQL statement against one of the two handles I previously defined in the following way:
$stmt=$pdo_db1Handle->prepare($mySQLStatement);
$stmt->execute();
When I try to do this, an error shows up telling me missing credentials for the DB_2. It happens the opposite (missing credentials of DB_1) if I try to execute it against pdo_db2Handle.
How should I proceed? any solution using PDO for this?
Thanks in advance :)
You can't join if you have to use separate PDO connections, so use nested loops and join the data in PHP.
$stmt_user = $pdo_db1Handle->query("SELECT id, username FROM t_users");
$stmt_score = $pdo_db2Handle->prepare("SELECT score FROM t_scores WHERE id_user = :userid");
$results = [];
while ($row_user = $stmt_user->fetch(PDO::FETCH_ASSOC)) {
$scores = [];
$stmt_score->execute(':userid' => $row_user['id']);
while ($row_score = $stmt_score->fetch(PDO::FETCH_ASSOC)) {
$scores[] = $row_score['score'];
}
$results[$row_user['username']] = $scores;
}
This will create an associative array whose keys are usernames and values are an array of their scores.
Depending on your use case, a work around may be to copy the table from one database to another temporarily and the perform your sql once you have both tables in a single database:
$pdo1 = new PDO('mysql:host=$db1_hostName; dbname=$db1_name', $db1_userName, $db1_password);
$pdo2 = new PDO('mysql:host=$db2_hostName; dbname=$db1_name', $db2_userName, $db2_password);
$insert_stmt = $pdo2->prepare("INSERT INTO T_SCORES (col1, col2, col3, ...) VALUES (:col1, :col2, :col3, ...) ON DUPLICATE KEY IGNORE");
$select_results = $pdo1->query("SELECT * FROM T_SCORES");
while ($row = $select_results->fetch(PDO::FETCH_ASSOC)) {
$insert_stmt->execute($row);
}
-- now work with the tables as you usually would.
You can create the table in the target database before hand and truncate the data before and/or after performing the insert.

How to make Mysql Queries not case-sensitive?

I have table which contain [Username, Email] and I'm checking them for non repeating any of them,
but It's case-sensitive , so if there is user that's Username is "SelvsterTP", if other user typed it, he won't be able to register, but if he type "selvstertp" for example, no errors face him! ,
I think of making extra column called 'UsernameCheck' and upload to it Username 'lowercase' , then check on that column (same with Email) ,
but it seems to me not the best code for that situation, so any ideas or suggestions?
Original code
$CheckusernameRow =
RowCountDB("Id","users","Username",$Username); //function
to get rows
My Idea
$CheckusernameRow =
RowCountDB("Id","users","UsernameCheck",strtolower($Username));
Did you try the LOWER() selector?
$lowerUsername = strtolower($Username);
$query = "SELECT id FROM users WHERE LOWER(Username) LIKE '$lowerUsername'";

Column count doesn't match value count at row 1 when submitting a form

I've been fighting with a bit of code for a week now, not seeing what the heck is wrong...
I have a gaming site I'm trying to build new character sheets for, the form is all done, the action pointing to another page that is strictly the sql for inserting the information into the database. We have good connection, but it is hanging at the second insert statement. The code was working previously, but we had to delete the database and rebuild it, resulting in a rebuild of the insert sql lines.
The first portion of the insert code is:
if($_POST['Submit']=="Submit")
{
$sql="INSERT INTO accounts (log_name,owner,account_type,date_joined) VALUES (\"$_POST[char_name]\",\"$_SESSION[logname]\",\"$_POST[account_type]\",NOW())";
$result = mysql_query($sql)
or die("<p>Couldn't add character.<br/>".mysql_error()." in accounts.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
echo $_SESSION['logname'];
$sql="INSERT INTO topdata (log_name,char_venue,sub_venue,species,char_name,create_date,gender,age,appage,nature,demeanor,concept,description,web_site,view_pword,sfa) VALUES (\"$_SESSION[logname]\",\"$_POST[char_venue]\",\"$_POST[sub_venue]\",\"$_POST[species]\",\"$_POST[char_name]\",NOW(),\"$_POST[gender]\",\"$_POST[age]\",\"$_POST[appage]\",\"$_POST[nature]\",\"$_POST[demeanor]\",\"$_POST[concept]\",\"$_POST[description]\",\"$_POST[web_site]\"\"$_POST[viewpw]\",\"$_POST[sfa]\")";
$result=mysql_query($sql)
or die ("<p>Could not create character.<br/>".mysql_error()." in topdata.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
When the information is entered into the form and submit is hit, I get the following:
1
Could not create character.
Column count doesn't match value count at row 1 in topdata.
Please send this exact message to Savvannis with your character's name.
I look at the database and the information is entered into the accounts table, so that statement is working, but it is hanging up on the topdata table. It's not echoing the $_SESSION['logname'] and looking at the database, it's not saving the owner, which should be $_SESSION['logname'], so I'm wondering if that statement is now somehow incorrect??
I can't figure out what the heck is wrong. Any and all help would be greatly appreciated.
You have missed a comma here: \"$_POST[web_site]\"\"$_POST[viewpw]\" in your second insert SQL.
It should be \"$_POST[web_site]\", \"$_POST[viewpw]\"
First off the error message is telling you that there is an unequal number of columns and values in your SQL
Lets have a look at that
INSERT INTO topdata (
log_name,
char_venue,
sub_venue,
species,
char_name,
create_date,
gender,
age,
appage,
nature,
demeanor,
concept,
description,
web_site,
view_pword,
sfa
) VALUES (
\"$_SESSION[logname]\",
\"$_POST[char_venue]\",
\"$_POST[sub_venue]\",
\"$_POST[species]\",
\"$_POST[char_name]\",
NOW(),
\"$_POST[gender]\",
\"$_POST[age]\",
\"$_POST[appage]\",
\"$_POST[nature]\",
\"$_POST[demeanor]\",
\"$_POST[concept]\",
\"$_POST[description]\",
\"$_POST[web_site]\"\"$_POST[viewpw]\",
\"$_POST[sfa]\"
)";
Now by formatting your SQL (which is vulnerable to sql injection) I've noticed a missing comma between web_site and viewpw values

mysql_query does not work partially when loading from sql file

I have dumped the contents of a database in an sql file in a form like
insert into `a` values
(17,11,5),
(18,12,7),
(19,12,10),
(21,14,45),
(22,15,46),
(24,16,46),
(25,16,49),
(26,17,21),
(27,17,30),
(28,17,45),
(29,17,54),
(30,18,32),
(31,18,35),
(32,19,23),
(33,19,27),
(34,19,54),
(35,20,53),
(36,21,32),
(37,21,35),
(38,21,45),
(39,22,23),
(40,22,30),
(41,22,45),
(57,24,19),
(58,25,46),
(59,26,39),
(60,27,49),
(61,27,56),
(62,28,34);
insert into `b` values (14,'2009-01-06',''),
(15,'2009-02-01',''),
(16,'2009-03-01',''),
(17,'2009-03-25',''),
(18,'2009-04-05',''),
(19,'2009-04-17',''),
(20,'2009-04-18',''),
(21,'2009-04-19',''),
(22,'2009-04-23',''),
(24,'2009-07-05',''),
(25,'2009-08-02',''),
(26,'2009-08-07',''),
(27,'2009-09-06',''),
(28,'2009-09-14','');
etc..
I have 4 such tables with no foreigh key constrains. Then I try to upload the data into the db (mysql). I read the file's contents, I pass each table's insertion into an array and then i do mysql_query for each element :
$sqlArray = explode(';',$sqlFile);
for($i=0;$i<sizeof($sqlArray);$i++){
mysql_query($sqlArray[$i]) or die ('Error: '.mysql_error());;
}
The result is that the last three tables are inserted but the first one is not, and the error 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 ' insert into `a` values (17,11,5), (18,12,7), (19,12,10), (21,14,4' at line 1
I validated that the $sqlArray has the correct contains and the queries are correct and runnable from phpmyadmin.
The problem seems to be regardless of the first table (i.e. it will show up even if b was first) and it always seems to "cut" the query in the middle (or after almost 70 characters).
Any help will be appreciated!
Your second statement has a typo ("int" should be "into"):
insert int `b` values (14,'2009-01-06',''),
Alternately, if that's not the issue, try using separate insert statements to get a clearer error message:
insert into `a` values (17,11,5);
insert into `a` values (118,12,7);
...
I have experienced on some older versions of MySQL that they don't like the extended inserts. You can also try specifying the column names explicitly with the real names of your columns. This would be useful if you have more than 3 columns in those tables (an auto-increment column for example).
insert into `a` (`[column1name]`, `[column2name]`, `[column3name]`) values (17,11,5);

entering datas of php page to database

I have a php form with two text boxes and i want to enter the text box values into the database. I have created the table (with two columns namely webmeasurementsuite id and webmeasurements id) I used the following syntax for creating table:
CREATE TABLE `radio` (
`webmeasurementsuite id` INT NOT NULL,
`webmeasurements id` INT NOT NULL
);
Utilising the tutorial in the following link, I wrote the php coding but unfortunately the datas are not getting entered into the database. I am getting an error in the insert sql syntax. I checked it but i am not able to trace out the error.Can anyone correct me? I got the coding from http://www.webune.com/forums/php-how-to-enter-data-into-database-with-php-scripts.html
$sql = "INSERT INTO $db_table(webmeasurementsuite id,webmeasurements id) values
('".mysql_real_escape_string(stripslashes($_REQUEST['webmeasurementsuite
id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['webmeasurements id']))."')";
echo$sql;
My error is as follows:
INSERT INTO radio(webmeasurementsuite id,webmeasurements id) values ('','')ERROR: 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 'id,webmeasurements id) values ('','')' at line 1
Because your table names have a space in them, you have to always surround them in backticks. Try this for your query:
$sql = "INSERT INTO $db_table(`webmeasurementsuite id`,`webmeasurements id`) values ('".mysql_real_escape_string(stripslashes($_REQUEST['webmeasurementsuite id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['webmeasurements id']))."')";
Looking at your pastebin, it looks like you have forgotten to close your input tags:
<input TYPE="text" name="webmeasurementsuite id"

Categories