Setup single record MySQL and PHP - php

How to set a single record to a user profile? For example username, password, email, and wallet. I need to show only date for each user login. This script shows wallet but first user id person and I need to show the user who is logged in.
HTML and PHP:
<?php
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT wallet FROM users LIMIT 1");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
while($record = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

To answer you fully.
Start by updating your user table when your users log in by changing the status true or false depending on your implementation.
Also start a session
your code now becomes
<?php
session_start();
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Login logics
$res= mysqli_query($con,"SELECT * FROM users where username='user' and password ='pass'");
if($res)
{
$user = mysql_fetch_row($res);
//Keep track of the current logged in user
$_SESSION['user'] = $user['id'];
}
//Now your logic to get wallet or any other thing for the current logged in user
$currentUser = $_SESSION['user'];
$result = mysqli_query($con,"SELECT wallet FROM users where id=".$currentUser.");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
$record = mysqli_fetch_row($result)
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
echo "</table>";
mysqli_close($con);
?>
Hope this helps..
Work with the Edit you dont need the While loop since you are looking for just a record

Related

How to select mysql row where idu is the same as SESSION id

So i am making a small website and want to select a mysql row where the idu in the row is the same as Session id of the user which is just logged into the site, the session works great on other pages of the site but i am helpless with this, see the codes below
<?php
include('solutions/session.php');
$id ='';
$id= $_SESSION['id'];
$page_name = 'settings';
$con=mysqli_connect("localhost","root","usbw","company");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM payment WHERE idu='$id'");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['wallet'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
and session.php looks like this
<?php
$connection = mysql_connect("localhost", "root", "usbw");
$db = mysql_select_db("company", $connection);
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysql_query("select username from wallet where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
header("location: index.php");
mysql_close($connection);
}
?>
First of all your session.php file code is not working because you are using mysql_query and also passing the connection that cause error use mysqli_query()
$ses_sql = mysqli_query($con,"select username from wallet where username='".$id."' ");
$row = mysqli_fetch_assoc($ses_sql);
//then set your session variable most imortant is id which is usefull
$_SESSION['id'] = $row["id"];
Rest of the things are good
Try replacing this line:
$result = mysqli_query($con,"SELECT * FROM payment WHERE idu='$id'");
with this one:
$result = mysqli_query($con,"SELECT * FROM payment WHERE idu=".$id);

Two many records showing when h_id is identified

I am trying to filter a mysql table using PHP, My aim is when the url is History.php?h_id=1 it only shows the rows that have one in the h_id (H_id is not a unique number)
My code is as below.
<html>
<head>
<title></title>
</head>
<body >
<?php
mysql_connect('localhost', 'root', 'matl0ck') or die(mysql_error());
mysql_select_db("kedb") or die(mysql_error());
$h_id = (int)$_GET['h_id'];
$query = mysql_query("SELECT * FROM Hist WHERE H_ID = '$h_id'") or die(mysql_error());
if(mysql_num_rows($query)=1){
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
?>
<?php
$con=mysqli_connect("localhost","root","matl0ck","kedb");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Hist");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>H_ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['DateMod'] . "</td>";
echo "<td>" . $row['H_ID'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I try to use this it shows all records that has a number in the h_id when I delete a number in this column it shows an error.
My table layout is as below.
Thank you
This is your syntactically incorrect statement
if(mysql_num_rows($query)=1){
A test is done using == and = is a value assignment
if(mysql_num_rows($query) == 1){
//------------------------^^
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
Also
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements and therefore stick to the mysqli_ or PDO database extensions
Your general code seemed to get a bit confused, and you were getting data from a query "SELECT * FROM Hist" that you never seemed to use.
Also the while loop was being terminated before you actually consumed and output the results of the first query.
I also amended the code to use parameterized and prepared queries, and removed the use of the mysql_ which no longer exists in PHP7
<?php
// Use one connection for all script, and make it MYSQLI or PDO
$con=mysqli_connect("localhost","root","matl0ck","kedb");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// if connection fails there is no point doing anything else
exit;
}
//$h_id = (int)$_GET['h_id'];
// prepare and bind values to make the code safe from SQL Injection
// also only select the rows you want
$sql = "SELECT ID, Name, DateMod, H_ID FROM Hist WHERE H_ID = ?";
$stmt = $con->prepare($sql);
if ( ! $stmt ) {
echo $con->error;
exit;
}
$stmt->bind_param("i", $_GET['h_id']);
$stmt->execute();
if ( ! $stmt ) {
echo $con->error;
exit;
}
// bind the query results 4 columns to local variable
$stmt->bind_result($ID, $Name, $DateMod, $H_ID);
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
if($con->affected_rows > 0){
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
while($stmt->fetch()) {
while($row = $stmt->fetch_array()) {
echo "<tr>";
echo "<td>$ID</td>";
echo "<td>$Name</td>";
echo "<td>$DateMod</td>";
echo "<td>$H_ID</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo 'No entry found. Go back';
}
?>

inserting into SQL with PHP

Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>

Delete a database entry not working

I have two pages, the first shows all items from a particular field in a MySQL database:
DatabaseEntries.php
<?php
include('connect.php');
$result = mysqli_query($db, "SELECT * FROM names")
or die(mysqli_error($db));
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Firstname</th> <th>lastname</th> <th>Email</th><th></th> ";
while($row = mysqli_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
?>
the second page contains the delete function:
Delete.php
<?php
include('connect.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['email']) )
{
// get id value
$email = $_GET['email'];
// delete the entry
$result = mysqli_query($db, "DELETE FROM names WHERE email=$email")
or die(mysqli_error($db));
// redirect back to the view page
header("Location: DatabaseEntries.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: Error.php");
}
?>
I get the following error when trying to delete an item from the database:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com' at line 1
Can anyone tell me why? and what to do to fix it?
Thanks
Add quotes around the $email
DELETE FROM names WHERE email='$email'

Display result from database in two columns

EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.

Categories