For the past couple days, I have been trying to learn how to search an mysql database. So far I have the code below. for some reason it isn't searching and giving me results back. my database is named score and the table is all scores. Someone please help me with this.
It should be searching my database but it's coming up with no results. I have made sure everything is correct.
This file is searching.php
<?php
if (isset($_POST['search'])) {
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "root", "score");
$query = "SELECT `name` FROM `all_scores` WHERE `id` = $id LIMIT 1";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
}
} else {
echo "Undifined ID";
$gameid = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$gameid = "";
}
this is search.php
<!DOCTYPE html>
<html>
<head>
<title> PHP FIND DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
</body>
</html>
To get the form values inside the php file you need to use $_POST. Here's an example using PDO. You're only retrieving one row so you don't need the while loop.
searching.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $conn->prepare("SELECT `name` FROM `all_scores` WHERE `id` = :id LIMIT 1");
$q->bindValue(':id', $_POST['id'], PDO::PARAM_STR, 50);
$q->execute();
if ($q->rowCount() > 0) {
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
Html:
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
Take some time look at several other examples
Related
This is my second topic tonight, but it's only because I can't really find any helpful information in regards to updating data in SQL using php. For some reason this won't update. If anyone has any suggestions that would be great :), again sorry for asking another question, I'm just eager to learn from my mistakes.
HTML Section:
<html>
<head>
<title>Update Data</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="editphpscript.php" method="post">
ID To Update: <input type="text" name="id" required><br><br>
New Status: <select name="status" required>
<option>Status</option>
<option value="Assigned">Assigned</option>
<option value="Pending">Pending</option>
<option value="No_Signal">No Signal</option>
<option value="Installed">Installed</option>
</select>
<input type="submit" name="update" value="Update Data">
</form>
</body>
</html>
PHP Section
<?php
// php code to Update data from mysql database Table
if(isset($_POST['update']))
{
$hostname = "";
$username = "";
$password = "";
$databaseName = "";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// get values form input text and number
$id = $_POST['id'];
$status = $_POST['status'];
// mysql query to Update data
$query = "UPDATE `leadlist` SET `status`='".$status." WHERE `id` = $id";
$result = mysqli_query($connect, $query){
($result){
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($connect);
}
?>
I would like to delete a row from my users table when the user clicks a button, the user needs to be logged in do delete their own account.
I have echo'd the $user_id which shows '4', which is the correct id for the logged in user, so user_id = $user_id
This is the page that I have which holds the button which I want to delete the users row in the database
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Welcome - <?php print($userRow['user_email']); ?></title>
</head>
<body>
<div class="header">
<div class="right">
<label><i class="glyphicon glyphicon-log-out"></i> logout</label>
</div>
</div>
<div class="content">
Welcome <?php print($userRow['user_name']); ?> <br>
<?php print($userRow['team_name']);?><br>
Rank <?php print($userRow['user_rank']); ?> <br>
Players
Teams
<form action='teams.php' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
<?php echo $user_id?>
</div>
</body>
</html>
I think your problem is your form action(teams.php) which will receive the post data.Your delete code is on the same file and logically $_POST['leave'] will never be set in this page.
Just try to remove your teams.php in your forms action attribute.
<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
or in your teams.php file add your delete code
//Make sure you have started the session before using it
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
Another piece of advise is use parameterize query.
Example:
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = ? ");
$stmt-> bindParam(1,$user_id);
$stmt->execute();
}
<?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);
} ?>
Delete
<?php if(isset($_GET['id'])){
$user_id = $_SESSION['user_session'];
$id=$_GET['id'];
if($id==$user_id){
$sql = "DELETE FROM Tablename WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
}?>
I am trying to create a login page using wamp server kindly help me with the following code
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql ="SELECT * FROM users WHERE username ='$username' AND password ='$password'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result==1))
{
echo "logged in successfully"."<br/>";
}
else
{
echo "invalid password or username retry";
}
}
?>
<html>
<head>
<title>login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="login" method="post" action="login.php">
Username <input type="text" name="username">
<br/><br/>
Password <input type="password" name="password">
<br/><br/>
<input type="submit" value="login" name="submit">
</form>
</body>
</html>
I think you had read some wrong articles and messed up .The correct code should be like this
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
// This line connects to DB
$con = mysqli_connect($host, $user, $pass,$db) or die ("Please check your server connection.") ;
if(isset($_POST['username']))
{
// use mysqli_real_escape_string to prevent SQL Injection
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
//write a query to select
$sql ="SELECT * FROM users WHERE username ='".$username."' AND password ='".$password."'";
//execute the written query using mysqli_query()
$result = mysqli_query($con,$sql);
//----------------------^----------- This is the missed parameter
//check the no of rows returned
if(mysqli_num_rows($result) == 1) { echo "logged in successfully"; }
else { echo "invalid password or username retry"; }
}
The line
if(mysqli_num_rows($result==1)) // You are passing boolean parameter here.
is incorrect
It should be:
if(mysqli_num_rows($result)==1) // You are passing result set here, which is expected.
I have that people can add team names to my MySQL table. Now I want them to edit it. I have tried several tutorials but i can't figure it out. I like to know what i am doing wrong.
This is my admin.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html>
<body>
<h1>Add teams</h1>
<form action="e2admin.php" method="POST">
<input type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form>
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo $row['Team']. "<a href='edit.php?edit=$row[1]'>Bewerk</a><br>";
}
}
?>
</body>
</html>
The add teams works. but the edit button doesn't work yet. If I click on edit I go to the edit.php page; here I want to add the new name and need the Team to change in the MySQL row.
This is my edit.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if( isset($_GET['edit'])) {
$id = $_GET['edit'];
$res = mysql_query("SELECT * FROM e2teams");
$row= mysql_fetch_array($res);
}
if (isset ($_POST['nieuwenaam'])) {
$newname = $_POST['nieuwenaam'];
$id = $_POST['id'];
$sql = "UPDATE e2teams SET Team='$newname' WHERE id='$id'";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php'>";
}
?>
<html>
<body>
<form action="edit.php" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"s" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
I also like to know how to delete team names but this is maybe for a next question.
This should work:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$id = intval($_GET['edit']);
if($id > 0) {
$res = mysql_query("SELECT * FROM e2teams WHERE `id` = $id");
$row= mysql_fetch_array($res);
$newname = mysql_real_escape_string($_POST['nieuwenaam']);
if (!empty($newname)) {
$sql = "UPDATE e2teams SET Team='$newname' WHERE id=$id";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php?edit=$id'>";
}
}
?>
<form action="edit.php?edit=<?= $id; ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
Edit: Also, about the intval() and mysql_real_escape_string(). Since you were using $_GET without any filter, I've added intval() function on it. Without filtering $id you could've been easily attacked by some sort of e.g. SQL Injection. Same with mysql_real_escape_string(). You might read about this filter function in php manual. For further study I recommend changing mysql_ functions to PDO or mysqli prepared statements. Happy coding!
Check your edit form. You have to put the value attribute like this value="s" no like value"". I think thats all.
I assume when they click on the edit link it's passing the id of the team so the edit.php select should be something like:
$id = (int)$_GET['edit'];
if (!empty($id))
{
$sql = "SELECT * FROM e2teams WHERE id='$id'";
$result = mysqli_query($sql);
$row = mysql_fetch_assoc($res);
}
//... keep the rest of code as is
Now you need to change the HTML form to:
<form action="edit.php?edit=<?php echo $row['id'] ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" value="<?php echo $row['Team'] ?>" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"<?php echo $row['id'] ?>" /><br>
<input type="submit" value="Update" />
</form>
I have written this code to create a search form and get results from mysql table:
<?
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_database = 'jatc_university_j32';
// Database Connection String
$con = mysql_connect($db_hostname, $db_username, $db_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="FieldValue" /><br />
<input type="submit" value="Submit" />
</form>
<?
if (!empty($_REQUEST['FieldValue'])) {
$FieldValue = mysql_real_escape_string($_REQUEST['FieldValue']);
$result = mysqli_query($con, "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'");
while ($row = mysqli_fetch_array($result)) {
echo $row;
echo "<br>";
}
}
?>
</body>
</html>
In my database table I have FieldName: candidatname, candidatsurname and FieldValue: John, Wayne etc.
I want to search entering a name and return the other details for this candidate
Anyway when I run code nothing happens
Can you please check if I am doing wrong something because I get the same result in a lot of trials
1.Nothing happens beacuse you are using <? ?> for php, but you should use <?php ?>
2.Your form method is post then you should check variblae like this on form submit:
if (!isset($_POST['FieldValue']))
3. "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'"
instead of candidatename, give the value that you got from the form:
"SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = '".$FieldValue."'" <BR>
4. <input type="submit" value="Submit" /> add a name property to this like:
<input type="submit" value="Submit" name="Submit"/>
and it will work, i tested after applying these changes!
Try this:
<?php
$formpartone = <<<EODformpartone
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="get">
Search: <input type="text" name="FieldValue" value=""/><br />
<input type="submit" value="Submit" />
</form>
EODformpartone;
$formparttwo = <<<EODformparttwo
</body>
</html>
EODformparttwo;
if (!isset($_GET["FieldValue"]))
{
echo $formpartone;
echo $formparttwo;
}
ELSE {
function search_candidate(){
$host = "localhost";
$user = "root";
$password = "";
$database = "jatc_university_j32";
$searchstring = $_GET["FieldValue"];
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$query = "SELECT candidatename, candidatesurname
FROM (
SELECT c.SubmissionID,
max(CASE WHEN c.FieldName='candidatename' THEN c.Fieldvalue ELSE 0 END) AS 'candidatename',
max(CASE WHEN c.FieldName='candidatesurname' THEN c.Fieldvalue ELSE 0 END) AS 'candidatesurname'
FROM mf2sn_rsform_submission_values as c
GROUP BY c.SubmissionID
) a
WHERE a.candidatename LIKE '".$searchstring."' OR a.candidatesurname LIKE '".$searchstring."'";
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>".$row['candidatename']."</td><td>".$row['candidatesurname']."</td></tr>";
} echo "</table>";
}
mysqli_close($link);
}
echo $formpartone;
echo search_candidate();
echo $formparttwo;
}
?>
Sample table mysql
CREATE TABLE candidates
(
id int auto_increment primary key,
SubmissionID int,
FieldName varchar(20),
Fieldvalue varchar(30)
);
INSERT INTO candidates
(SubmissionID, FieldName, Fieldvalue)
VALUES
(1,'candidatename','Bob'),
(1,'candidatesurname', 'Smith'),
(2,'candidatename','Jack'),
(2,'candidatesurname', 'Doe');
SQLFiddle demo of the sample data
You should look into the validation and sanitation of the search string to avoid SQL injection. And what to do when no candidates are found with the name you inserted. However, I think for now it is important to test if everything works.