Issue of running sql query from php code - php

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.

Related

PHP: Autocomplete inputs when MySQL table element selected

I'm building a simple app to send confirmation emails. I have a MySQL table with 4 columns: id, user_email, user_name and user_track. The form consists of a selectbox that shows all the user_email stored and two text inputs that should be autocompleted when an email is selected.
I have tried the following, but it just echo's all the entries for user_track and user_name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
$option = '';
$artist = '';
$track = '';
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$option .= '<option value = "'.$row['user_email'].'">'.$row['user_email'].'</option>';
$track .= '<input type="text" name="track" required value = "'.$row['user_track'].'">';
$artist .= '<input type="text" name="artist" required value = "'.$row['user_name'].'">';
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<h1>Accepted demo</h1>
<form action="demo.php" method="post">
<select name="select">
<?php echo $option; ?>
</select><br><br>
<?php echo $track; ?><br><br>
<?php echo $artist; ?><br><br>
<input type="date" name="date" placeholder="Release Date" required>
<br><br>
<input style="margin-top:10px;" class="btn" type="submit" value="Send email">
</form>
</body>
</html>
<?php
$conn->close();
?>
update From
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
To
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data WHERE user_email='".$_POST['selected_user_email']."' ORDER BY id DESC";
where selected_user_email is the name of input field that is being posted

PHP only adding Numbers to sql in column of VARCHAR

PHP only adding Numbers to MySQL in column of VARCHAR instead of texts
when using query directly in MySQL it works...but if I use $_POST from HTML, IT fails
I don't know the reason how it is getting failed. what is the problem here ?
<?php
$link=mysqli_connect("localhost","root","","home_ac");
if(mysqli_connect_error()) {
die("error in database");
}
$name =$_POST["name"];
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,$name)";
if(mysqli_query($link, $query)){
echo "done";
}
else {
echo "failed";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="enter a name" name="name">
<input type="submit" value="add">
</form>
</body>
</html>
You need quotes around text
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,'$name')";
Please, think about prepared query. It solve quotes problem and protect from SQL injection.
You have to use PHP Prepared Statements or PHP Data Objects (PDO).
For example, using PDO:
<html>
<head>
<meta charset="utf-8">
<title> Example PDO Insert </title>
</head>
<body>
<form method="post" action="" name="myForm" id="myForm">
<input type="text" placeholder="Enter Your Name" name="name" required="required">
<input type="submit" name="submit" value="add">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "home_ac";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['submit']) && !empty($_POST['name']) ) {
# code...
$sql = "INSERT INTO test (number,name) VALUES (NULL,'$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

how to search sql database using php

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

Form Data will not insert to database

I have connected my website to my database successfully when i submit the form it goes through but nothing is getting inserted into the database.
Code Below:
<?php
if( $_POST )
{
$con = mysql_connect("server","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buycruisesdb", $con);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_name = mysql_real_escape_string($users_name);
$users_email = mysql_real_escape_string($users_email);
$query = "
INSERT INTO `website_subscribers`(`name_sub`, `email_sub`) VALUES ([$users_name],[$users_email])";
mysql_query($query);
echo "<h2>Thank you for subscribing!</h2>";
echo $query;
echo $users_name;
echo $users_email;
mysql_close($con);
}
?>
buycruisesdb = database
website_subscribers = table inside the database
name_sub/email_sub = columns inside the table
the form html is below:
!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="php/subscriber.php" id="form" method="post" name="form">
<input id="name_sub" name="name" placeholder="Name" type="text">
<input id="email_sub" name="email" placeholder="Email" type="text">
<input type="submit" value="Submit" name="f_submit">
</form>
</body>
</html>
Not sure exactly why this is not inputing anyone have an idea?
it says that it is inserting the proper values and into the proper tables
Image
Square brackets are not valid in MySQL queries. You should be using quotes around the strings.
$query = "INSERT INTO `website_subscribers` (`name_sub`, `email_sub`) VALUES ('$users_name', '$users_email')";
change it to:
$query = "
INSERT INTO website_subscribers (name_sub,email_sub) VALUES ('".$users_name."','".$users_email."') ";
just copy the code and try it out

Unable to insert mysql database through form data

I have created a form where I want to insert mysql database when I submit the values but when I click on the submit button the database isnt updated.. dont know where I am going wrong in my code..
<html>
<head>
<title>Form Data</title>
</head>
<body>
<form action="form.php" method="post">
Server Name: <input type="text" name="server_name"> <br />
IP Address: <input type="text" name="ip_address"> <br />
Server Role: <input type="text" name="server_role"> <br />
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "abcx";
$dbname = "serverasset_inventory";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$sql = "INSERT INTO asset_inventory (server_name,ip_address,server_role)
VALUES ('$_POST[server_name]','$_POST[ip_address]'),'$_POST[server_role]')";
$state = mysqli_query($connection,$sql);
mysqli_close($connection);
}
?>
</body>
</html>
Any help?
-A
you are using a extra bracket between query and missing quote in variable's use like below
$sql = "INSERT INTO `asset_inventory` (`server_name`,`ip_address`,`server_role`)
VALUES ('".$_POST['server_name']."','".$_POST['ip_address']."','".$_POST['server_role']."')";
if you want to insert the fields
for example
your sql will be take in variables then insert it in sql
$server_name = $_POST['server_name'];
$ip_address = $_POST['ip_address'];
$server_role = $_POST['server_role'];
insert into asset_inventory (server_name,ip_address,server_role) VALUES ('$server_name','$ip_address','$server_role';

Categories