Check PostgreSQL tables before insertion - php

I have to insert several values in a PgSQL Table using these variables
$knr = $reader->getAttribute('Nr');
$kname = $reader->getAttribute('Name');
And this insertion code:
$SQL = "";
$SQL .= "SELECT
(konzern).knr AS knr, (konzern).name AS name
FROM konzern";
$SQL .= "INSERT INTO konzern (";
$SQL .= "knr, name";
$SQL .= ") VALUES (";
$SQL .= "'".$knr."', '".$kname."'";
$SQL .= ");".PHP_EOL;
And I want to check if the table "Konzern" already have a row with the $knr and if yes it should insert into this, if not it should create a new row
$query = doQuery("select nr from konzern where knr = '".$knr."'");
$num_rows = ($query->num_rows);
if ($num_rows > 0) {
// do nothing
}
else {
$sql .= "select nextval('konzern_nr_seq')";
}
But I have some problems puting this into the right order.
Can someone complete this code?

You can do this with a single query in this way :
INSERT INTO konzern SELECT val1, val2
WHERE NOT EXISTS(
SELECT nr from konzern where knr = 'var1'
)
Implement this approach it will be more straigth forward .
And remember to use query parameters instead of concatenating the query text, to avoid SQL Injections.

Related

how to select id from one table and insert into other table

$select = "SELECT MAX(order_id) FROM `order`";
mysql_query($select);
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
$result2 = mysql_query($query1);
The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id
$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
while($data = mysqli_fetch_assoc($row))
{
$order_id = $data['order_id'];
}
}
//This way you can fetch data
Then use this while inserting value for order_id in your query as in
$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";
one another way to find last inserted id from the db connection:
mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
then $id will be last inserted id
Recommendation:
Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.
Used method:
Extract maximum of order_id from order and assign to $maxOrderId.
Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.
In the end implode the $insertRowValues array into the batch INSERT statement.
Run the batch INSERT query - only once.
<?php
$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);
$insertRowValues = array();
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}
$query1 = "INSERT INTO `cart`
(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
VALUES " . implode(', ', $insertRowValues);
$result2 = mysql_query($query1);
Other recommendations:
Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);
Use exception handling;
Use prepared statements to avoid MySQL injection.
P.S: I couldn't test anything.
Good luck!

Dynamic sql search in php

Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !

MySQL search method through PHP

Quick question on a method to search mysql database with php.
Right now, I have a function that is supposed to search and return results. Say I have two databases, one being User and one being Profile. User stores the username, email, password. while Profile stores user first name, last name, address, birth day. Right now, I'm not sure how to go about this, but this is what I have so far.
I want to be able to search both tables and return a list of results via a table which I've got covered, but I don't know how to get the intricacies down.
The function will contain either NULL or value of the variable. Right now, this is my sketch up:
if(!empty($username)):
$append .= "WHERE";
$append .= "username = ".$username."";
endif;
if(!empty($email)):
$append .= "WHERE";
$append2 .= "email= ".$email."";
endif;
if(!empty($firstname)):
$append .= "WHERE";
$append2 .= "firstname = ".$firstname."";
endif;
if(!empty($lastname)):
$append .= "WHERE";
$append2 .= "lastname= ".$lastname."";
endif;
$sql = "select * FROM Users ".$append."";
$result = mysql_query($sql);
$sql2 = "select * FROM Profile ".$append2."";
$result2 = mysql_query($sql2);
$userId = mysql_fetch_row($result2);
$userId['id'] = $id; <-- this is the one I will call to display data.
How can I efficiently do this and search/return all unique/distinct user ID's? Both tables include a user ID / incremented ID number (User table is User_ID, Profile table is acct_id). I know this code is a bit wrong... Don't worry about escaping - I;'ve gotten that sorted. Should I use a JOIN statement?
Other problem I am facing is changing between WHERE and AND because sometimes if one var is set but another isn't, then we must use AND instead of just one WHERE. Any idea how to tackle this issue?
Thanks for your input!
For your WHERE clause it is probably best to use arrays and then implode() like this
$and_where = array();
if (!empty($username))
$and_where[] = "username = ".$username;
if (!empty($email))
$and_where[] = "email = ".$email;
//etc
if (count($and_where) > 0)
$where = " WHERE ".implode(" AND ", $and_where);
else
$where = "";
Are the two tables related in some matter? If acct_id is a foreign key to User_id you can just use an INNER JOIN ($where as shown above)
$query = "SELECT Users.col, ..., Profile.col, ... FROM Users
INNER JOIN Profile ON Users.user_id = Profile.acct_id".$where;
If they aren't, you could simply UNION them
$users_and_where = array();
$profiles_and_where = array();
if (!empty($username))
$users_and_where[] = "username = ".$username;
if (!empty($email))
$users_and_where[] = "email = ".$email;
//etc
if (!empty($firstname))
$profiles_and_where[] = "firstname = ".$firstname;
if (!empty($lastname))
$profiles_and_where[] = "lastname = ".$lastname;
//etc
if (count($users_and_where) > 0)
$users_where = " WHERE ".implode(" AND ", $users_and_where);
else
$users_where = "";
if (count($profiles_and_where) > 0)
$profiles_where = " WHERE ".implode(" AND ", $users_and_where);
else
$profiles_where = "";
$query = "(SELECT col1, col2, ... FROM Users".$users_where.")
UNION
(SELECT col1, col2, ... FROM Profile".$profiles_where.")";
You should try to avoid * in your queries and select the rows specifically, this way you don't have too much overhead in the future, when additional columns are introduced that your code doesn't use here.

How to get and store timestamp in database

How can I automatically send date/time info to my database when my form is submitted? I'm making a comment box, and I have a column in my "comments" table called "created" (which I've set as a "datetime" type) where I would like date and time information to be sent so I can display it with the comments on my page.
Is this something I would have to send from my page's code, or can I set up the database in a way that it automatically stores a time stamp every time it receives new data from the form? I'm using phpMyAdmin to manage my database, in case that helps.
This is the code I have right now for sending the form's information:
<?php
if (isset($_POST['submit'])) {
$required_fields = array("author", "body");
validate_presences($required_fields);
if (empty($errors)) {
$author = mysql_prep($_POST['author']);
$body = mysql_prep($_POST['body']);
$page_name = ($_POST['page_name']);
$query = "INSERT INTO comments (";
$query .= " author, body, page_name";
$query .= ") VALUES (";
$query .= " '{$author}', '{$body}', '{$page_name}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
redirect_to("new_admin.php");
} else {
// Failure
$_SESSION["message"] = "There was an error that prevented the comment from being saved.";
}
}
} else {
$author = "";
$body = "";
}
?>
Any help would be awesome, thanks!!
Would look something like this:
$query = "INSERT INTO comments (";
$query .= " author, body, page_name, date_Added";
$query .= ") VALUES (";
$query .= " '{$author}', '{$body}', '{$page_name}', NOW()";
$query .= ")";
$result = mysqli_query($connection, $query);
Also you may need to
ALTER TABLE comments ADD date_added date time;
or you could have the database populate it for you by adding a column like so:
ALTER TABLE comments ADD date_Added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
In your db table definition you can set a default value for fields, including timestamp/datetime on new rows and on updates. This means you wouldn't have to change the above code (given the above scenario).
http://dev.mysql.com/doc/refman/5.1/en/timestamp-initialization.html

inserting values from a loop

$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')";
}
this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?
You’re probably executing the query after the loop so only the last record is being inserted.
Try to execute the insertion query at the end of the loop:
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
mysql_query($sql2);
}
Or you first collect all data and then do one query to insert all records:
$values = array();
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
}
if (!empty($values)) {
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values);
mysql_query($sql2);
}
But don’t forget to prepare the values for the query (see mysql_real_escape_string function).
If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement.
Example:
INSERT INTO registered (ServiceID, IDno, Stype)
SELECT field1, field2, field3
FROM class
WHERE SubjID='$SubjName' and SecID='$SecName'"
And like written before me, escape your variables...
Note: make sure you're escaping your variables with mysql_real_escape_string.
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ";
$addComma = false;
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')";
$addComma = true;
}
Change this line:
$sql2="INSERT INTO registered..."
to this:
$sql2 .= "INSERT INTO registered..."
inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.

Categories