Kind note: Practicing PHP
I got the CRUD library from this repo: https://github.com/rorystandley/mysqli-crud-php-oop.
I setup the database, connected to to it and everything is great. I am only unaware of how to use this globally?
I have different pages for different data tables, I see it not logical to create multi "insert.php" files for each page.
Insert.php:
<?php
include('class/mysql_crud.php'); // Contains the server info (locahost, user, pass, table)
$db = new Database();
$db->connect();
$data = $db->escapeString("name5#email.com"); // Escape any input before insert
$db->insert('CRUDClass',array('name'=>'Name 5','email'=>$data)); // Table name, column names and respective values
$res = $db->getResult();
print_r($res);
I believe include(); won't solve it as each page has different data to pass around.
Should I create a condition for "if that page, then pass this data"??
Thanks in advance.
Related
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
I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples
I have a database with a table called translations. It has several columns, but I am trying to create a session array to house a variale:translations named array.
I've tried the below code, but I must be missing something... my end goal is to populate much of the static verbiage of a website using $_SESSION['TRANSLATIONS']['Userboards'] for example to populate the names of otherwise static content into any language supported based on the database.
$querylang = "SELECT variable,translation FROM translations left outer join languages on languages.abbrev = translations.fkabbrev WHERE languages.abbrev = 'EN'";
$sqllang = mysql_query($querylang);
while($reslang = mysql_fetch_array($sqllang)){
$_SESSION['TRANSLATIONS'][$reslang['variable']] = $reslang['translation'];
};
The above code is actually correct. The reason it didn't work was a separate issue. Thanks to #Epodax for reminding me to check the errorlog!
I have a mySQL database table setup called site.
Rather than qet the column headings to produce a PHP object of values I want to produce data from the rows.
TABLE: site
:::field:::::value:::::
url www.example.com
name example site
etc Example Etcetera
So I want to be able to get this information from the server by calling the column name I want and the row I am after. I want to do this for all fields in site as I don't want to do multiple calls for the various different rows in site; I'd rather store all the information from the beginning in the object:
eg. <? echo $site['url']; ?>
I created this put it appears to be causing an error:.
$sql = "SELECT * FROM `site`";
$site[];
foreach($sodh->query($sql) as $sitefield){
$site[$sitefield['field']] = $sitefield['value'];
}
Obviously I've missed something. ¿Any idea as to what?
$site[];
should be
$site = array();
I'm trying to display the data here in order of:
Author Name
Book Name
Url
NOTE: There are many results for each piece of data. Im not sure how they are stored in the array when they are fetched.
The database schema is relational as you will see and connects these bits of information from different areas of the database.
Im new to programming as you may have figured.
Im at a loss here.
Here is my code:
<?php
//Starting session
session_start();
//Includes mass includes containing all the files needed to execute the full script
//Also shows homepage elements without customs
include ('includes/mass.php');
//Set the session variable
$username = $_SESSION['username'];
//Check to see if logged in
if (isset($username))
{
//Check all databases assoc with the notes for username submissions
$sql_for_username_submission = "SELECT notes.authname, notes.bookname, notes.url, notes.note_id, notes.user, smallnotes.chapter_name FROM notes INNER JOIN small_notes ON notes.note_id = small_notes.notes_id AND notes.user = small_notes.user ORDER BY notes.note_id";
$get_data = mysql_query($sql_for_username_submission);
while ($data_row = mysql_fetch_assoc($get_data))
{
$authnames = $data_row['authname'];
Stopped here. not sure how to progress
}
}
?>
I would imagine you need some UI controls to which you would bind the data in data_row. In other words, you need to have some placeholders on the screen.
Best Regards
You are fetching my assosciative array so it does not matter. You can just reference the array item by key and use it whenever and where ever you want.
You do not have to worry about how the array is sorted.