Creating link to database - php

I am currently making a project on Universal Identification Number(not such a big one, but like that kind of....upto college level)..I want to create a page with tabs to the respective databases.... like If I press key 'A' for a tab then all the names starting with letter 'A' should appear...
Plz help me !!!!
Regards !!

Not entirely understanding your question, but if I was to create a tab for different names, and/or situations, I'd use a switch statement with cases that allows you to change the order_by in your sql query.

I think this is kinda what you want to display all names starting with an A passed on with a get request:
<?php
//connect to mysql database (if you don't know search google)
if(isset($_GET['namestartingwith'])){
$namebegin = $_GET['namestartingwith'];
$query = mysql_query("SELECT * FROM database WHERE name LIKE \"$namebegin%\"");
while(mysql_fetch_array($query) = $data){
echo $data['name'];//name being the name op your column with the name data
}
}
?>
This should do the trick for php+mysql

In Java+MySQL, after downloading and instating the requisite jars:
public static Connection dbConnect() throws SQLException, ClassNotFoundException {
String DB_URL;
Class.forName("com.mysql.jdbc.Driver");
DB_URL = "jdbc:mysql://your_db_url?autoReconnect=true";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
return conn;
}
In the calling program,
public static Object dbExecute() throws SQLException, ClassNotFoundException {
Statement stmt;
Connection conn = dbConnect();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("your_sql_statement");
Object result = null;
while (rs.next()) {
result = rs.getObject("field_you_want_to_retrieve");
}
rs.close();
stmt.close();
conn.close();
return result;
}

I think you need to take this from the start. Are you using PHP or Java? Are you using MySQL or Oracle for your database? Maybe set yourself a simpler goal, build a PHP page (or Java servlet) that fetches data from your database and displays it in a table in the web browser. When you get this working, you can build on it.
When you get to a question that you can't answer, then submit that question to Stackoverflow. Explain what you have working, what you are trying to do and where the expected result deviates from the actual result.

Related

SELECT WHERE = sybol dont return data

a have an sqlite table
CREATE TABLE "lib" (
"id" INTEGER UNIQUE,
"addr" TEXT UNIQUE,
"data" TEXT,
PRIMARY KEY("id")
)
testing dataset contains:
...
1 arara arararar test
2 unit=comp comp test
...
I use code next to test requests
<? $db = new PDO('sqlite:main.db') or die('Unable to open database');
echo ("qry: ".$_SERVER["QUERY_STRING"]."<br>");
foreach ($db->query("SELECT * FROM lib WHERE addr='".$_SERVER["QUERY_STRING"]."'", PDO::FETCH_ASSOC/*_NUM*/) as $row) {
//echo($row[0].'<br>');
echo($row['addr'].'<br>');
echo($row['data'].'<br>');
}
$db = null; ?>
so, when I do script.php?arara it returns
qry: arara
arara
arararar test
but, when I do script.php?unit=comp it returns no data (just QUERY_STRING)
qry: unit=comp
what wrong with my code?
upd:
this question is not about security
php modified for PDO prepare, now its return no data with any request
<? $db = new PDO('sqlite:main.db') or die('Unable to open database');
echo ("qry: ".$_SERVER["QUERY_STRING"]."<br>");
$qry=$db->prepare("SELECT * FROM lib WHERE addr='?'");
$qry->execute(array($_SERVER["QUERY_STRING"]));
foreach ($qry as $row) {
//foreach ($db->query("SELECT * FROM lib WHERE addr='".$_SERVER["QUERY_STRING"]."'", PDO::FETCH_ASSOC/*_NUM*/) as $row) {
//echo($row[0].'<br>');
echo($row['addr'].'<br>');
echo($row['data'].'<br>');
}
$db = null; ?>
what wrong with my code?
... sadly quite a lot.
I've never seen someone inject the QUERY_STRING straight into a query. How easily corruptable would this string be? If I wanted to inject some malicious sql I just have to write it in. If I make a mistake then the query won't return anything. If I add a new parameter in the future because I want more than a single param then the query fails.
The malicious sql is the most dangerous problem here, the other's are about code maintainability and still very important. Check out this
https://bobby-tables.com/
and this
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
You need to parse the query string so you can check and sanitise the data. Php has an in-built function for this:
https://www.php.net/manual/en/function.parse-str.php
You then should be binding the data in the prepared statement you have now read about.
I don't know if you're in charge of the script calling this, but it seems like POST data would be better for this. GET parameters are visible and stored in web server logs, so you have a security vulnerability with potential personal data. You also then won't need to worry about url_encoding/decoding the string.
//EDIT
to be fair, using PHP's parse_str with decode the url anyway, so that at least will take care of that issue if you can't convert it to post

Passing function result into sqli

I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script

How to dump MySQL table to a file then read it and use it in place of the DB itself?

because a provider I use, has a quite unreliable MySQL servers, which are down at leas 1 time pr week :-/ impacting one of the sites I made, I want to prevent its outeges in the following way:
dump the MySQL table to a file In case the connection with the SQL
server is failed,
then read the file instead of the Server, till the Server is back.
This will avoid outages from the user experience point of view.
In fact things are not so easy like it seems and I ask for your help please.
What I did is to save the data to a JSON file format.
But this got issues because many data on the DB are "in clear" included escaped complex URLs, with long argument's line, that give some issue during the decode process from JSON.
On CSV and TSV is also not workign correctly.
CSV is delimited by Commas or Semilcolon , and those are present in the original content taken from the DB.
TSV format leave double quotes that are not deletable, without avoid to go to eliminate them into the record's fields
Then I tried to serialize each record read from the DB, store it and retrive it serializing it.
But the result is a bit catastrophic, becase all the records are stored in the file.
When I retrieve them, only one is returned. then there is something that blocks the functioning of the program (here below the code please)
require_once('variables.php');
require_once("database.php");
$file = "database.dmp";
$myfile = fopen($file, "w") or die("Unable to open file!");
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
fwrite($myfile, serialize($row));
}
fclose($myfile);
mysql_close();
// Retrieving section
$myfile = fopen($file, "r") or die("Unable to open file!");
// Till the file is not ended, continue to check it
while ( !feof($myfile) ) {
$record = fgets($myfile); // get the record
$row = unserialize($record); // unserialize it
print_r($row); // show if the variable has something on it
}
fclose($myfile);
I tried also to uuencode and also with base64_encode but they were worse choices.
Is there any way to achieve my goal?
Thank you very much in advance for your help
If you have your data layer well decoupled you can consider using SQLite as a fallback storage.
It's just a matter of adding one abstraction more, with the same code accessing the storage and changing the storage target in case of unavailability of the primary one.
-----EDIT-----
You could also try to think about some caching (json/html file?!) strategy returning stale data in case of mysql outage.
-----EDIT 2-----
If it's not too much effort, please consider playing with PDO, I'm quite sure you'll never look back and believe me this will help you structuring your db calls with little pain when switching between storages.
Please take the following only as an example, there are much better
way to design this architectural part of code.
Just a small and basic code to demonstrate you what I mean:
class StoragePersister
{
private $driver = 'mysql';
public function setDriver($driver)
{
$this->driver = $driver;
}
public function persist($data)
{
switch ($this->driver)
{
case 'mysql':
$this->persistToMysql($data);
case 'sqlite':
$this->persistToSqlite($data);
}
}
public function persistToMysql($data)
{
//query to mysql
}
public function persistSqlite($data)
{
//query to Sqlite
}
}
$storage = new StoragePersister;
$storage->setDriver('sqlite'); //eventually to switch to sqlite
$storage->persist($somedata); // this will use the strategy to call the function based on the storage driver you've selected.
-----EDIT 3-----
please give a look at the "strategy" design pattern section, I guess it can help to better understand what I mean.
After SELECT... you need to create a correct structure for inserting data, then you can serialize or what you want.
For example:
You have a row, you could do that - $sqls[] = "INSERT INTOsong(field1,field2,.. fieldN) VALUES(field1_value, field2_value, ... fieldN_value);";
Than you could serialize this $sqls, write into file, and when you need it, you could read, unserialize and make query.
Have you thought about caching your queries into a cache like APC ? Also, you may want to use mysqli or pdo instead of mysql (Mysql is deprecated in the latest versions of PHP).
To answer your question, this is one way of doing it.
var_export will export the variable as valid PHP code
require will put the content of the array into the $data variable (because of the return statement)
Here is the code :
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
$content = array();
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
$content[$row['ID']] = $row;
}
mysql_close();
$data = '<?php return ' . var_export($content, true) . ';';
file_put_contents($file, $data);
// Retrieving section
$rows = require $file;

mongodb php multiple collections

A bit of weird issue - I am looking to enter data into two separate
collections (same db) and I am getting totally weird results. I am
sure it is the way I am doing this but it is the results which have me
a bit baffled.
Here is a snippet of what I am trying to accomplish:
$mynewconnection = new Mongo(); // create new mongo connection
$collectionDB = $mynewconnection->Datadb; // select db
$collectionA = $collectionDB->DataA; // select collectionA
$collectionB = $collectionDB->DataB; // select collectionB
/* Go off and chop up data and create CriteriaA/B */
$insertA = $collectionA->insert($criteriaA);
$insertB = $collectionB->insert($criteriaB);
So what I am trying accomplish is to enter part of the data set into
one collection and the other part of the dataset into another
collection. What is happening is that sometimes the data will be
entered into Both collections (as desired) and other times data will
be entered into just collectionA and yet other times data will be
entered into just collectionB.
Anyone have any ideas on what I am missing or what would be causing
this strange behavior?
When you fire a query to write something to MongoDB, it does not confirm whether the data is written to database or not. You need to see the page of php's manual for Write Concerns.
The link for the same is: http://www.php.net/manual/en/mongo.writeconcerns.php

mysql wrong column increment

what is wrong with this code?
$core->query("UPDATE games SET hits = hits + 1 WHERE id=".intval($id).";");
hits incerements by 2 and sometimes by 3! I mean for example hits = 3; when I call this function, hits will be 5 and sometimes 6! (add 2 and 3 instead 1).
mysql table type is MyISAM.
query function is:
function query($query) {
$this->error="";
$this->result=#$this->link->query($query);
if(!$this->result) {
$this->error=#$this->link->error;
return FALSE;
}
return $this->result;
}
link is:
$link = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
The SQL code looks correct, so it must be the context that is causing the problem.
It is possible that you put the code in an element that gets called two or three times per page? If not explicitly, through an include or subroutine structure?
It seems that your query is correct but may be this function call for multiple time for same $id value. Please check this..
thanks
It was from flash on that page.

Categories