how to turn a php session into a usable variable - javascript

i have created a site were i have 2 tables on a database. the first page has 2 links which when clicked sends the name of the link to a php session. it then takes you to a page were its meant to view ether one of the databases based on the data that has been saved In the php session.
what i am trying to achieve is to have those links open up the table inside that file that will open up when the link is clicked. i don't want to make a new .php file for every table since i want to be able to simply add and access those tables on one document but not more then one.
that is my problem. on that document were it sends me to access the table from my database i want to access in variable (code below). the code below will explain what i need to know.
this is the code which i view the data in my table
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
>
the code below is were i want to have the variable that has the name of the link i clicked on the page which gets redirected to this when the link is clicked. the variable that i gather from the php session i want to appear at the tablenamehere text.
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
the code i have so far which creates the php session but is not connected to links yet are below.
<html>
<body>
Register Now!
</body>
</html>
<?php
session_start();
?>
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
echo "the veriable is " . $_SESSION['link'] . "<br>";
i only want multiple tables to open up in this one php file. thank you for helping, any questions please message below.

If we can assume you are passing a table name as a parameter ( bit dangerous ) then you can do this
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
$sql = "SELECT id, firstname, lastname
FROM {$_SESSION['link']}
ORDER BY id
DESC LIMIT 500";
But a better way might be to pass an indicator to the table you want to use. This way you are not passing a real table name around in the ether for people to see
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
switch ($_SESSION['link']) {
case : 'a'
$tbl_name = 'table1';
break;
case : 'b'
$tbl_name = 'table2';
break;
default:
$tbl_name = 'default_table';
}
$sql = "SELECT id, firstname, lastname
FROM $tbl_name
ORDER BY id
DESC LIMIT 500";

My guess: the script that accesses the database is test1.php. The link adds already the call parameter a (=newtable):
Register Now!
The script test1.php could honor this $_GET parameter like you do when setting the $_SESSION parameter. The modification of your code would then look like this:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get and sanitize table name
$tablename = $conn->real_escape_string($_GET['a']);
$sql = "SELECT id, firstname, lastname FROM $tablename ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
// ....
Notes:
In my example I assume that all tables are handled the same way. Of course, you could differentiate code based on the value of $tablename.
You most probably would not need a $_SESSION variable.
If, for any reason you must use a $_SESSION variable $_GET['a'] obviously should be overwritten by $_SESSION['link'] or vice-versa.
For security reasons, do not forget to sanitize the input parameter $_GET['a']!

Related

how to call and echo a value from my database for a a certain user using username to identify the user

I have a table named users on my database which is suppose to hold balance in BTC and Cash in two of its rows
I have a php file which i have used to echo the value for each user using the user's username to identify the particular user, but for some reason the echoed data contains the whole row for BTC and Cash value instead of identifying the user using the username and displaying only the value in the column for BTC and Cash where it suppose to display the balance on my website.
So what i am basically looking for is the code to call the data from my database and using username to identify user, display the value for the user.
This is the html where it suppose to display the user's balance on my website
<!doctype html>
<html>
<div class="logged-user-w text-center avatar-inline">
<div class="logged-user-info-w">
<div class="logged-user-name">
<a class="text-primary" href="profile.php"><?php echo $_SESSION['username']; ?></a>
</div>
//BTC balance//
<div class="logged-user-role">
<a class="text-grey" href="wallet.php"><?php include('new.php')?></a>
</div>
//Cash balance//
<div class="logged-user-role">
<a class="text-grey" href="cashwallet.php"><?php include('new.php')?></a>
</div>
</div>
</html>
hare is the php (new.php) which is suppose to get the values from my database and echo it
<?php
// Server credentials
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Creating mysql connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking mysql connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Writing a mysql query to retrieve data
$sql = "SELECT * FROM users bitcoin, cash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Show each data returned by mysql
while($row = $result->fetch_assoc()) {
?>
<!-- USING HTML HERE : Here I am using php within html tags -->
<p> <?php echo $row["bitcoin"]; ?></p>
<p> <?php echo $row["cash"]; ?></p>
<?php
}
} else {
echo "0 results";
}
// Closing mysql connection
$conn->close();
?>
Your sql query is wrong change it to
$sql = "SELECT * FROM users";
Or if you just want the fields like bitcoin and cash you may write a query as
$sql = "SELECT bitcoin,cash FROM users";
And then echo the respective variables.
As stated by Kunal Raut, change your sql statement, but if you want to select the data based on the username, then use the following.
$sql = "SELECT bitcoin, cash FROM users WHERE username=$_SESSION[‘USERNAME’]”
Or use the user id.
$sql = "SELECT bitcoin, cast FROM users WHERE userid= $_SESSION[‘USERID’]
In both examples, you would need to change the field name to match what you used in the database to hold either the username or the user id.

How to send information (return) from php to javascript

I'm currently trying to code a dumb website for a class. I'm trying to access my PHP file to check if the name exists inside the database or not. When it does, it needs to return either a 1 or 0 back to the javascript part. Is there a real way to do that?
The reason for the return is in case the name does exist, it will just send an alert to the user that hey the name exists, move along.
Note I'm using the tutorials from w3school.com in case my code looks like some amateur level sh*t.
javascript:
function checking(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "checker.php?firstname=" + firstname + "&lastname=" + lastname, true);
xmlhttp.send();
alert (queue);
}
php:
<?php
session_start();
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$yes = 1;
$no = 0;
//Information needed in order to access database
$dbname = "**********************";
$servername = "localhost";
$username = "************************";
$password = "************";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = "SELECT firstname, lastname FROM queue_1 WHERE firstname='".$firstname."' and lastname='".$lastname."'";
$result = mysqli_query($conn,$sql_query);
$row = mysqli_num_rows($result);
if($row == 1){
echo ($yes);
}
else
{
echo ($no);
}
?>
I see a few issues here, your JS code is attempting to access an undefined variable (at least in the context of the function you posted) queue.
Outside of your PHP code, make sure that the JS is handling the response coming from PHP, do this by attaching an event listener to your request.
The load event will trigger when your PHP script completes, you can point this to a named function if your code will be more complex than just an alert.
More info here MDN Docs
function checking(){
var xmlhttp = new XMLHttpRequest() ;
xmlhttp.addEventListener("load", function () {
alert(this.responseText);
});
xmlhttp.open("GET", "checker.php?firstname=" + firstname + "&lastname=" + lastname, true);
xmlhttp.send();
}
This is under the assumption that you're trying to display the response text as an alert message.
Additionally, beware passing unfiltered user input into an SQL query, this can lead to injection attacks, I'd suggest you change your PHP code to use prepared statements from the mysqli lib.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql_query = "SELECT firstname, lastname FROM queue_1 WHERE firstname=? AND lastname =?";
$stmt = $conn->prepare($sql_query) ;
$stmt->bind_param('s', $firstname);
$stmt->bind_param('s', $lastname);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows === 1 ? $yes : $no;
$stmt->free_result() ;
$stmt->close() ;
More info about mysqli can be found here if some of this is confusing mysqli documentation
And on a final note, on your sql if you are looking for the existence of a record only, it tends to be faster to do SELECT 1 FROM table WHERE fieldname=? LIMIT 1 as you are not using the result set for this.

How can I store audio and video files with phpMyAdmin

So my original plan was to store images and audio in the directory with my html, css etc. but when I went to write my js, I found out I couldn't use require(fs)(I need to be able to search for these things) which threw a loop in my plan. My backup plan is to create a phpMyAdmin database to store my audio and images. I'm not sure how I could do this, or if it's even possible. Could someone point me in the right direction? Thanks so much.
Edit: I realized it might be possible to alter my Javascript so it does work so here it is.
const fs=require('fs')
var files = []
fs.readdir("Assets/Cards", (err, files) => {
files.forEach(f_name => {
files.push(f_name);
});
})
console.log(files)
Just save the media in the database in a column like media_content (it being varchar of course)
Just do something like
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
if this doesn't work try rebooting your server (this only works on linux and WINDOWS NT 5.1 or lower)

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

Load txt from SQL Database

I have a html code with javascript that loads the data from the same directory or a given folder, that's to say the url is just "folder/text.txt".
However, if I want to extract and read this file from a mySQL database named for example exampledb, how can I indicate the new url in my code in order to import the data with Javascript just as I did with a local file?
Thanks!
You will need to use a server side programming language to talk with your database, I would strongly recommend PHP or looking into some more advanced technology like Angular.js along side Node.js!
Here is a quick PHP/mysqli example on pulling data and displaying it in a table.
taken from w3
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
There is several ways to tackle this, that is just a start.
http://www.w3schools.com/php/php_mysql_select.asp

Categories

Resources