I am new to php. I want to fetch a particular data from mysql and display it in the label.I have tried a simple php coding.But it displays the fetched data two times(actually I have created 2 columns such as name and age in a table called test).Please help me.Here is the coding:
displayform.php
<body>
<form method="post" name="display" action="display.php" >
Enter the name you like to display the data from MySQL:<br>
<input type="text" name="name" />
<input type="submit" name="Submit" value="display" /> </form>
</body>
</html>
display.php
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("acp")or die("Connection Failed");
$name = $_POST['name'];
$query = "select age from test where name = '$name'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result))
{
echo $line['age'];
echo "<br>\n";
}
?>
The datas in table is
name=janani
age=25
The output is displayed as
25
25
I am certain that you have two rows bearing the same name and/or age.
In order to show only one result, what you need to do is:
Use either DISTINCT with GROUP BY, or LIMIT 1.
I.e.:
$query = "select DISTINCT age from test where name = '$name' GROUP BY name";
or
$query = "select age from test where name = '$name' LIMIT 1";
Sidenote: I suggest you use mysqli with prepared statements though, since your code is open to SQL injection.
<?php
$DB_HOST = "xxx"; // Replace
$DB_NAME = "xxx"; // with
$DB_USER = "xxx"; // your
$DB_PASS = "xxx"; // credentials
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
if($statement=$conn->prepare("select age from test where name = ? LIMIT 1")){
// or this one
// if($statement=$conn->prepare("select distinct age from test where name = ? group by name")){
$name = "janani";
$statement-> bind_param("s", $name);
// Execute
$statement-> execute();
// Bind results
$statement-> bind_result($age);
// Fetch value
while ( $statement-> fetch() ) {
echo $age . "<br>";
}
// Close statement
$statement-> close();
}
// Close entire connection
$conn-> close();
$line = mysql_fetch_array($result) ; //remove while loop
echo $line['age'][0];
try this ans this is work for one data fetch from table .. And may possible your result show two time because $name match two times in table so it fetch two record
You are hard coding 'age' in the array reference so it will echo that element only. Loop over array by index and you will get the name also.
Related
I am trying to filter out data from my table using a searchbox in HTML. My search box which should return value from SQL query.
But even if I search, the filtered table is not displayed.
I have checked the 'LIKE' query in phpMyAdmin with '%n' (which I meant an entry in my table ending with 'n' ) and it works, but since in mine I am searching for a specific text that is entered in the search box, I couldn't check for the query that I am using.
Would really appreciate any help and thanks in advance.
<?php
//error_reporting(E_ERROR | E_PARSE);
$db_host = 'localhost';
$db_user = 'zamil'; // Username
$db_pass = '1234'; // Password
$db_name = 'resi'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
else{
print("connected");
}
$output = '';
$query = '';
if (isset($_GET['search'])){
$searchq = $_GET['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE 'Rep Name'
LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'There was no entries';
}else{
while ($row = mysqli_fetch_array($query)) {
$cname = $row['Source of Content'];
$rname = $row['Rep Name'];
$output .= '<div>'.cname.' '.rname.'</div>';
}
}
}
if ($query != 0) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<form action="Sales1.php" method="post">
Search: <input type="text" name="search" />
<input type="submit" value="Search" /><br />
</form>
<?php print("$output"); ?>
</body>
</html>
Your SQL query is incorrect:
SELECT * FROM 'salesflow' WHERE 'Rep Name' LIKE '%$searchq%'
You put single quotes (') around the salesflow table name and Rep Name column name but you should use backticks (`) instead.
For more information see Using backticks around field names.
I think you have entered a wrong query syntax.
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%$searchq%'") or die("could not search!");
It should be written like this:
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%".$searchq."%'") or die("could not search!");
Always use ' for string in query.
Also, my additional recommendation is not to use SQL for searching in the table, instead, use DataTable based on AngularJS.
I need only to display the last values in the row. Now its displaying
Message for: Rocha : gff
Message for: Rocha :
Message for: Rocha : hi my name is kenny
I only need it to display Message for: Rocha : hi my name is kenny.
Thank you
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, className, lastname, messages FROM Mymesages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if("CPS210-CompSci-I (4)"==$row["className"] && $lastname== $row["lastname"]){
echo "Message for: " . $row["lastname"]. " : " . $row["messages"]. "<br>";
}
}
}
$conn->close();
?>
If you're looking for only one record, that too the last one, you just need to modify your query a little. Also, there's no need for the loop in that case.
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
Replace this line:
while($row = $result->fetch_assoc()) {
With simply:
$row = $result->fetch_assoc();
If you want to display the last row, then your query should be like this:
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
And later, instead of while loop simply fetch the row like this:
$row = $result->fetch_assoc();
I am new at this and learning the code.
I want to create the php code which select the particular row.
say 5th row or 6th row any row.
I create the code like this
<?php
$servername = "localhost";
$username = "test1";
$password = "pass";
$dbname = "test1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FIELD1, FIELD2 FROM mytable ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["FIELD1"]. " - Name: " . $row["FIELD2"]. " <br>";
}
} else
{
echo "0 results";
}
$conn->close();
?>
THis code works fine but it give the all data of the table.I want to just select particular row number data.how to do this??
You can do it with the LIMIT statement, say LIMIT 3,1 to select the 4th row. First number is the starting row, second number is the count of rows to select.
$sql = "SELECT FIELD1, FIELD2 FROM mytable LIMIT $row_index, 1";
will give you row $row_index + 1
You can do it using WHERE condition in query as SELECT FIELD1, FIELD2 FROM mytable WHERE id = 1.
I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.
How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();