I'm using php to display what I have in my data base of user name.
When I want to delete the user name it works and deletes it from the database but it still shows in my php page.
Heres the delete command I'm using:
<table class="table">
<tr><th>#</th><th>Date</th><th>ID</th><th>Actions</th></tr><?php
if ($_GET['a'] == 'delete' && $_GET['i']) {
$UserId = $_GET['i'];
$res=mysql_query("SELECT FROM `users` WHERE `UserId`=$UserId");
$TraderId=mysql_result($res,0,"TraderId");
mysql_query("DELETE FROM `users` WHERE `UserId`=$UserId");
mysql_query("DELETE FROM `traders` WHERE `TraderId`=$TraderId");
echo '<br><br><div class="alert alert-warning"><strong>Bye bye!</strong> Result has been deleted.</div>';
}
if($_GET['s']=="true")
{
echo '<br><br><div class="alert alert-success"><strong>Success!</strong> The user has been saved.</div>';
}
$res = mysql_query("SELECT * FROM `users`");
for ($i = 0; $i < mysql_num_rows($res); $i++) {
$Username = mysql_result($res, $i, "Username");
$UserId = mysql_result($res, $i, "UserId");
$IsAdmin = (string) (bool) mysql_result($res, $i, "IsAdmin");
echo "<tr><td>$UserId</td><td>$Username</td><td>$IsAdmin</td><td>
Delete
Edit</td></tr>";
}
?>
</table>
and here is where the names should show .. this is the trader page where the TraderId is displayed:
<table border="">
<head><tr><th style="padding-bottom:40px; padding-right:70px; padding-top:20px;">Date</th><th style="padding-left:200px; float:right;">Screenshots</th></tr></thead>
<?php
$res=mysql_query("SELECT * FROM `traders`");
for($i=0;$i<mysql_num_rows($res);$i++)
{
$Name=mysql_result($res,$i,"Name");
$Price=mysql_result($res,$i,"Price");
$Timezone=mysql_result($res,$i,"Timezone");
$TraderId=mysql_result($res,$i,"TraderId");
echo '<tbody><tr><td style="padding-left:0px;padding-bottom:10px;">'.$Name.'</td><td style="padding-left:200px;"><a href="details.php?i='.$TraderId.'">View details<a/></td></tr></tbody>';
}
?>
</table>
Again the delete function works as I see the result been removed from my sql database but not from the output page.
$res=mysql_query("SELECT FROM `users` WHERE `UserId`=$UserId");
select what?
Guessing the delete users works as it gets the id from $_GET, where as the traders never actually gets any data from mysql query.
EDIT - longer explanation
The delete users works as your userid used on the delete query is provided without needing the select:
$UserId = $_GET['i'];
The delete traders wont work because you did not select anything to get the traders id from the user id to use on the delete query
$res=mysql_query("SELECT FROM `users` WHERE `UserId`=$UserId");
$TraderId=mysql_result($res,0,"TraderId");
ie "SELECT FROM users" - select WHAT?
Related
I"m trying to display names that connected to the same table.
There are 3 different DB tables:
Tables
Guests
Info
First I get the data from the "Table" to get the table id.
Than I get the data from the "Info" table to figure which guests are connected to the table id so I get their id's (can be multiple id's).
And last I get the name of every guest by it's id.
My issue is that I can only get the final name I'm expecting and not all names that are connected to the same table.
The last result needs to display each table and every name that connected to table.
PHP:
$sql_e1 = "SELECT `tid` FROM `table`";
$result_e1 = $con->query($sql_e1);
if ($result_e1->num_rows > 0) {
$i = 0;
while($row0 = $result_e1->fetch_assoc()) {
$table_id = $row0['tid'];
$array[$i]['table_id'] = $table_id;
$sql_e2 = "SELECT `id` FROM `info` WHERE `tid`='".$table_id."'";
$result_e2 = $con->query($sql_e2);
if ($result_e2->num_rows > 0) {
while($row2 = $result_e2->fetch_assoc()) {
$guest_id = $row2['id'];
$array[$i]['guest_id'] = $guest_id;
$sql_e3 = "SELECT `name` FROM `guests` WHERE `id`='".$guest_id."'";
$result_e3 = $con->query($sql_e3);
if ($result_e3->num_rows > 0) {
while($row3 = $result_e3->fetch_assoc()) {
$array[$i]['name'] = $row3['name'];
}
}
}
}
$i++;
}
}
$counter = 0;
HTML:
<?
if (isset($i)) {
while ($counter < $i) {
include 'infodialog.php';
?>
<div class="<? echo $array[$counter]['table_id']; ?>">
<p><? echo $array[$counter]['name']; ?></p>
</div>
<?
$counter++;
} } ?>
If you want to get multiple names in array your code should be:
$array[$i]['name'][] = $row3['name'];
Or according guest ids code should be
$array[$i][$guest_id]['name'][] = $row3['name'];
This will get all the names but you have to change your HTML code according array.
Another solution besides Rohit Rasela's is using JOINS. JOINS will be a much better solution in the long run especially when you start adding a lot of data and speed is important. It's been a while since I've done PHP and MySQL and I haven't tested this but it should work I believe:
MySQL:
SELECT
guests.name as GuestName,
table.tid as TableId,
info.id as InfoId
FROM table AS table
JOIN info AS info ON info.tid = table.tid
JOIN guests AS guests ON guests .id = info.[guest_id_column_name]
This will return a row for each match it finds when it goes through each table and you'll be able to loop through and access the GuestName, TableId and InfoId for each match. If you don't care about the table ids, you can leave them out in the SELECT list. You can add ORDER BY if the order matters.
HTML loop:
while ($row = $result->fetch_assoc()) {
<div>Guest name: <php echo $row['GuestName']; ?></div>
<div>Table Id: <php echo $row['TableId']; ?></div>
<div>Info Id: <php echo $row['InfoId']; ?></div>
}
You can get more information on JOINs at https://www.w3schools.com/sql/sql_join.asp
Hello I want to make a like system using PHP and MySQL when clicked on the like Button i also insert Data in the database but there is an error database value inserted but like value as 0 no increment and undefined error occurs . Can anybody help me solving this problem
There is my Like button code :
<?php
//// work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
//$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this code work fine without insert Data
There is My liked with Data Insertd Code
<?php
////work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error
The error is Undefined Variable
I also try $total_likes="";
as global but still not work
Your code suffers from a race condition. What you should be doing is this pattern:
INSERT INTO likes (uid, total_likes) VALUES (?, 1)
ON DUPLICATE KEY SET total_likes=total_likes+1
Where you use bind_param to set the placeholder value to your UID.
Note that in your one query you set the total count of all likes to be +1. This is a huge mistake.
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
I don't know if wrote something wrong in the query, or if it's a logic error. The problem is on the second to last line.
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
$num = mysql_num_rows($q1);
if($num==1){
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1)){
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(userId,visits,unique) VALUES('$userId','1','yes')");
?>
EDIT: userId and visits are both set to INT in the database.
i think first error in in variable name using in $ql and second is $num==1 if in visitors table multiple record of thats user then this condition will be wrong ($num==1) so i think replace it with this ($num>0)
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='$userId' ");
$num = mysql_num_rows($q1);
if($num>0)
{
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1))
{
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(`userId`,`visits`,`unique`) VALUES ('$userId','1','yes') ");
?>
You should add error handling to your sql queries, but the problem (after the correction indicated by #DanielLisik) is the use of a reserved word: unique.
Change your query to:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
You should also consider changing to PDO or mysqli as the mysql_* functions are deprecated.
1.
Change:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
to:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
2.
Delete the single quotes around $userId in your SQL queries (since it's an INT). It should be like this:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
and:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");
Now I have created a login form with a session, what I need now that when the user login with his username and password, get his data such as name, about etc.. and put it in the welcome page.
Currently I have created this code but this code get all users data,
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("usersdata") or die(mysql_error());
$data = mysql_query("SELECT * FROM userid")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['Name'] . "</td> ";
Print "<th>Username:</th> <td>".$info['Email'] . " </td></tr>";
}
Print "</table>";
?>
I hope to find a way to do that. :D
Since you already created a login form with session then you get the data for the current logged in user by doing this:
$_SESSION['userid']: Should be filled in the login page.
$_SESSION['userid'] = $id
Learn more about the sessions: PHP Sessions W3schools
And then:
$query= mysql_query("SELECT * FROM `userid` WHERE `id` = '".$_SESSION['userid']."' ")or die(mysql_error());
$arr = mysql_fetch_array($query);
$num = mysql_numrows($query); //this will count the rows (if exists)
HTML
<html>
//...
<?php if($num > 0){ ?>
<table border="1" cellpadding="3">
<tr><td colspan="2" align="center">Your Info</td></tr>
<tr>
<td>Name: <?php echo $arr['Name']; ?></td>
</tr>
<tr>
<td>Email: <?php echo $arr['Email']; ?></td>
</tr>
</table>
<?php }else{ ?>
User not found.
<?php } ?>
//...
</html>
Although you should use the mysqli_ extension, rather than mysql_, you would want something like:
$result = mysql_query("SELECT * FROM userid WHERE username = '" . $username . "'")
or die(mysql_error());
if(mysql_num_rows($result) == 1) {
//Found the user
$row = mysql_fetch_array($result);
//Results can be accessed like $row['username'] and $row['Email']
} else {
//Too few or too many records were found
}
Note: I've used username='$username' as an example. It would be best to track the user's ID from the login process as the ID refers to a specific row.
$data = mysql_query("SELECT * FROM userid")
Should be
$data = mysql_query("SELECT * FROM userid WHERE Name='$selectedName'")
Of course you need to define $selectedName
I also recommend you read http://dev.mysql.com/doc/refman/5.0/en/select.html to learn about some fundamentals.
Your example code retrieves all users from the database and loops through the data using a while loop.
To get the user that has logged in you need to change your query that fetches the data.
I'm assuming you have a primary key in your table and know the id because the user already logged in.
$data = mysql_query("SELECT * FROM userid WHERE id={$userid}");
$info = mysql_fetch_array( $data );
echo $info['Name'];
$info will now contain all the user info for 1 user, you need to fill $userid with the actual id from the user that is logged in.