returing one value from the database using php - php

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();

Related

not able to retrieve the last inserted id from sql in html

i am trying to display some values from database to my html calling the last inserted id
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from registers where id= LAST_INSERT_ID()";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " $row[firstname] ";
}
} else {
echo "0 results";
}
But when I am using this, the result is not being displayed, is there any problem with my code, how do I retrieve the last inserted id from sql?
try this query
$sql = "SELECT * from registers ORDER BY ID DESC limit 1 ";
it will give you only one result and this result will be the last inserted ID.
But ID needs to be auto increment.
To retrieve the last id in the table you need:
SELECT id FROM registers ORDER BY ID DESC LIMIT 1

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

Use PHP loop to fetch tables data from the table which contain names of database tables

I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

i want to execute a saved query in the database

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.

Categories