How to get user information from a MYSQL local database - php

Hey i need to get information from a database and display it on my index.php.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
however this will show the information for all of the users in the database.
I have a primary key in the database, which is the account number, could we use this to only display information about that account on the page only?
I will also need to save the details into variables on the php page so some guidance doing that would be greatfull.
Thanks Oliver

In order to retrieve data according to a specific user you must explicitly tell mysql. So, add WHERE id={the I'd u want the info for}.
For your second question. "How do u get the id when the user logs in".
The answer to this is you can (a) how a session initialized at login or (b) how another file or even a loop in the script you need the Id for to run a query for the users name and then you get the Id.
The draw backs of option b is that you are slowing this done and are doing alot of call which can crash your overall site.
The choice is your this is how you can get a particular I'd for a user.

<?php
include('session.php');
?>
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver'); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM username WHERE username='$login_session'"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['username'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['sex'] . "</td><td>" . $row['phone'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['password'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
I got the WHERE username="$login_session"
and the login_session value is a unique value for each of the users in the database so it can never be the same, so i can use this to pull up information for that user only

You can use session variables to store the information in the case you are working with sessions, if not, you can use a regular variable to store the information or maybe use post or get variables

Related

trouble getting info from an array and then inserting it into a db

I have a page that I have been working on. It runs several queries to get existing data from several tables in my DB. There is a table that shows the result of three queries. The first query gets the extension and the secret of phones, the 2nd query gets MAC addresses of phones, and finally the third query gets the names of templates for the phones. The results of the last two queries (with the help of others) are setup as dropdowns in the 3rd and 4th columns of the table created to show the extensions. This way I can select the MAC of the phone I want to assign to the extension and then the template to make the phone work the way I want. The whole page is set as a form and I am using $post to the insert page. My goal here is to take the information (array) that is created by the user making their selections and insert ALL the 4 columns of information into a new table, from there I want to create files using that information to setup the phones. Here is the code I have for now.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$link = mysql_connect("localhost", "root", "cacti") or die ('Error connecting to mysql' . mysql_error());
mysql_select_db("cqadmin");
$sql2 = "SELECT extension, secret from extensions;";
$result2 = mysql_query($sql2) or die(mysql_error());
echo "<table border='3'>
<tr>
<th>Extension #</th>
<th>Secret</th>
<th>MAC Address</th>
<th>Template</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
$sql = "SELECT id , mac FROM phones order by mac;";
$result = mysql_query($sql) or die(mysql_error());
$sql1 = "SELECT id , templatename FROM templates order by templatename;";
$result1 = mysql_query($sql1) or die(mysql_error());
echo "<tr>";
echo "<td>" . $row['extension'] . "</td>";
echo "<td>" . $row['secret'] . "</td>";
echo "<td> <select name='phone'>";
while($rowA = mysql_fetch_array($result)) {
echo '<option value="' . $rowA['id'] . '">' . $rowA['mac'] . '</option>';
}
echo "</select></td>";
echo "<td><select name='template'>";
while($rowB = mysql_fetch_array($result1)) {
echo '<option value="' . $rowB['id'] . '">' . $rowB['templatename'] . '</option>';
}
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" value="Submit your selections">
</body>
</html>
And my insert page
<?php
echo "You got here";
//***********Get the Assignment information *************
$values = array_values($_POST);
print_r($values);
?>
The resulting print shows this
Array ( [0] => 324 [1] => 24 )
Looking at my db table 324 is the index id of the last phone scanned and in the template table 24 is the last template created, No info on the extension or the secret.
I think I am close but I do not know where to go from here.
PS. I know I need to use mysqli or pdo, not sure how to change over yet.

PHP delete functionality probably logical error

In the top of my admin PHP (admin.php), I have loaded data from "Sport" table in "DogSport" MySQL database. After clicking "Edit" link of a particular record, I can
edit, delete that record on "editform2.php". Even on that page, I can also insert a new record.
Problem: Deleting first and second records do not work! Deleting all following records work fine. This problem only with deleting functionality.
Code segment - admin.php
<?php
include("dbconnect.inc.php");
//Retrieving Data
$query1="SELECT * FROM Sport ORDER BY SportId ASC";
$result2=mysqli_query($con, $query1);
$rows=mysqli_num_rows($result2);
$i=0;
if($rows==0)
echo "<br/>There are no records";
else{
echo "<table id='sport'>";
echo "<tr><th>Sport Id</th><th>Sport Name</th><th>Description</th></tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr><td>" . $row["SportId"] . "</td><td>" . $row["SportName"] . "</td><td>" . $row["Description"] .
"</td><td> <a href='editform2.php?id=" . $row["SportId"] . "' target='_blank'>Edit</a></td></tr>";
$i++;
}
echo "</table>";
}
?>
Code segment - editform2.php
if(isset($_POST["delete"])){
include("dbconnect.inc.php");
$query3="DELETE FROM Sport WHERE SportId=$id";
mysqli_query($con, $query3);
echo "<h1>Deleted Successfully</h1>";
mysqli_close($con);
}
I have uploaded necessary files, you can also use to check it including database .sql script. Your help is appreciated.
https://www.dropbox.com/s/wn40u93oa1sxcph/SO.rar?dl=0
$query3="DELETE FROM Sport WHERE SportId=$id";
Where did you set value of $id? It should be $_POST["id"] right?
As a side note - SQL injection risk ...

Deleting an item from a mysql cart with php

I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.
The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.
To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.

Deleting a row from the database via PHP

Okay, so what I've got here is a PHP generated table in which the values are pulled from a database. Now, if the administrator is logged in, I'd like to add an option to delete a row from the database.
I've got the structure all set up, but I have no idea what to put in the path of the link that is supposed to delete the row. How can I do this?
<?php
$rb = 1;
include 'konekcija.php';
$query = "SELECT * FROM oglasi";
$rezultat = mysql_query($query);
while($niz = mysql_fetch_array($rezultat)){
echo "<tr><td>" . $rb . "</td><td>" . $niz['model'] . "</td><td>" . $niz['cena'] . "</td><td><img src='" . $niz['slika_path'] . "'</img></td>";
if($_SESSION['uloga'] == "admin"){
echo "<td><a href='#'>Obrisi</a></td>";
}
echo "</tr>";
$rb++;
}
?>
You could try something like
echo "<td><a href='delete.php?row=" .$niz['id']. "'>Obrisi</a></td>";
Where delete.php is a php page that checks if the user is an administrator, parses the id value via GET (always remember to do proper escaping to avoid injections, or use other query systems, like prepared statements or stored procedures), and deletes the row with the specified id. Of course every record must have a unique id. Eventually the page redirects to the table view page.
Important sidenote: mysql_* functions are deprecated, use mysqli_* ones instead!
Well first of the link that you should use to delete the row is going to be whatever link you create.
Therefore you will have to create a new php page, or modify an existing one. To handle the requests to delete the rows.
Here is a quick example:
handler.php
<?php
//execute database connection here
switch($_GET['action'])
{
case 'delete':
mysql_query('DELETE FROM `TABLE_NAME` WHERE '.$_GET['where']);
break;
case 'add':
//parse info and submit request to db
break;
case 'edit':
//parse info and submit request to db
break;
}
//close db connection
?>
Disclaimer! This example is by no means secure, do not use it in production.
Then the absolute link you would use would be something like: (unescaped version)
http://host.com/pathtofile/handler.php?action=delete&where=(row_name='rowid')
guo
$rb = 1;
include 'konekcija.php';
$query = "SELECT * FROM oglasi";
$rezultat = mysql_query($query);
while($niz = mysql_fetch_array($rezultat)){
echo "<tr><td>" . $rb . "</td><td>" . $niz['model'] . "</td><td>" . $niz['cena'] . "</td><td><img src='" . $niz['slika_path'] . "'</img></td>";
if($_SESSION['uloga'] == "admin"){
echo "<td><a href='#'>Obrisi</a></td>";
}
echo "</tr>";
$rb++;
}
?>

php - using a hyper link to send variable used in data base to use get command to echoe results

I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!

Categories