How to fetch a word from a database using PHP? - php

This is the PHP code for fetching a word that was entered by the user. May I ask on how to show the result of "jhon dewey" if the user entered the keyword "john" on my website as "jhon" only without the last name?
My database fields are:
first_name (contains the first name records)
last_name (contains the last name records)
This is my code. Please help me find the error. Can I change the %john% into a variable so that any word entered by the user can search to my database?
<?php
// Database connection
$sql = new mysqli("localhost", "root", "MYPassword", "test");
if (mysqli_connect_errno ()) {
die(mysqli_connect_error());
exit;
}
$query = "SELECT * FROM `usage` WHERE 'first_name' LIKE %john%";
$result = $sql->query($query);
if (!$result)
die($mysqli->error);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close();
$sql->close();
print("<pre>");
print_r($rows);
print("</pre>");
?>

Patterns are string literals so they must be wrapped with single quotes.
Second, column names are identifiers so they shouldn't be wrap with single quotes as single quotes are for string literals.
Snippet:
$query = "SELECT * FROM `usage` WHERE `first_name` LIKE '%john%'"
Since your column name is not a reserved keyword, backticks are optional on this case
$query = "SELECT * FROM `usage` WHERE first_name LIKE '%john%'"

Check this one
<?php
// Database connection
$sql = new mysqli("localhost", "root", "MYPassword", "test");
if (mysqli_connect_errno ()) {
die(mysqli_connect_error());
exit;
}
$query = "SELECT * FROM `usage` WHERE `first_name` LIKE '%john%'";
$result = $sql->query($query);
if (!$result)
die($mysqli->error);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close();
$sql->close();
print("<pre>");
print_r($rows);
print("</pre>");
?>

Related

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

PHP Displaying data from MySQL database

I wanted to display a page content with PHP and MySQL. But i don't know how to select and display data from PHP.
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
But i don't know how to display data. I want to get the string value from content in sql table row where name = $name and display it.
If you can, please help me
You may try and include this in your code:
$name = mysqli_real_escape_string($_GET['title']);
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo $row['content'];
}
mysqli_free_result($result);
Here I have assumed $link as the handle to connect to the database.
N.B.: You may consider passing the $_GET values through mysqli_real_escape_string() to avoid sql injections which may prove fatal to the database and its tables. You also need to consider the usage of mysqli_* functions because mysql_* functions are deprecated and will be discontinued.
You have error in your sql, change
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
to
$query = "SELECT * FROM pages WHERE name = '".$name."'"; // as name is char it should be enclosed in quotes
$result = mysql_query($query); // using quotes inside this will just display it without executing the query
You can fetch the results by this (if the result is only single record):
$row=mysql_fetch_array($result); // fetch the result as an array with subscript as the field name
echo $row['content']; // echo the value of the field content
If the query result contains multiple records then you have to do this inside a while loop like this:
while($row=mysql_fetch_array($result)) // fetch the result as an array with subscript as the field name
{
echo $row['content']; // echo the value of the field content
}
you have to do like this
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = '".$name."'";
$result = mysql_query($query);
//get values returned from query
$row=mysql_fetch_array($result);
//display required content
echo $row['content'];
Also mysql_* function are deprecated.You have to stop using this. Start using PDO or prepared statements or mysqli_* function
First of all the mysql_ is deprecated, use mysqli_
<?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();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Source: http://www.php.net/manual/en/mysqli-result.fetch-array.php
$query = mysql_query("SELECT * FROM table WHERE name = $name");
$result = mysql_fetch_array($query);
//you'll get value in var
$var=$result['content'];
You can do this using Prepared Statements :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($value_you_want, $value_you_want_as_well);
while($stmt->fetch()){
echo $value_you_want . $value_you_want_as_well;
}
$stmt->close();
Or you can do this using PDO :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = :name";
$stmt = $connection->prepare($query);
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 20);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $page) {
echo $page->whatever1 . $page->whatever2;
}
$stmt = null; // Set to null to destroy connection

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.

PHP Query Breaking

I'm trying to call a database for the first time in PHP, and this query is causing my code to break. Note that I've tested the connection to be good. The culprit is mysql_query(). Can anybody spot what might be going wrong? The table name is "users" and the entry under the 'Name' column is 'mvalentine'. Everything matches case as far as I can tell.
dbInit.php
<?php
$connection = mysql_connect('localhost', 'root', 'password');
$db = mysql_select_db('scaleup');
if ($db) {
$user = mysql_query("SELECT ID FROM 'users' WHERE 'Name' = 'mvalentine'");
}
else {
die ('Error 01: Connection to database failed.');
}
?>
This modified code is now returning something. The value 'users' in the ajax call is now returning "false"
The value being returned should be '1'
ajax response:
<?php
include('dbInit.php');
include('objects.php'); //irrelevant, all code working properly
$layout = new Layout();
$bids = new Bids();
$out = array('layout' => $layout->_board, 'height' => $layout->_height, 'width' => $layout->_width,
'bids' => $bids->_board, 'maxBids' => $bids- >_maxBids, 'users' => $user);
$out = json_encode($out);
echo $out;
?>
It seems like you are expecting $user to contain the user ID, but it will actually contain a resource containing all of the rows returned. In order to get the user ID, you will need something like this:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'");
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
$row = mysql_fetch_assoc($result);
$user = $row['ID'];
}
Also, take note of the other comments and answers regarding style and the preference of mysqli and PDO for this type of thing.
What is "$db" in your if statement?
To connect to your database you must use "mysql_connect" and "mysql_select_db".
For example,
<?php
$connection = mysql_connect('localhost', 'root', 'password');
$db = mysql_select_db('database_name');
if($connection)
{
if($db)
{
//query here
} else {
die("Couldn't connect to mysql database ".mysql_error());
}
} else {
die("Couldn't connect to mysql host ".mysql_error());
}
?>
Also, it is good practice to surround table and column names with the prime character like so
mysql_query("SELECT * FROM `tablename` WHERE `column_name` = 'value'");
I can't verify this right now, but I believe you may have a syntax error in your query:
mysql_query("SELECT ID FROM 'users' WHERE 'Name' = 'mvalentine'");
Column and table names, if you wish to quote them, should use the back tick:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'");
Then change the rest of your code to actually fetch the user details:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'") or die("Query failed");
$row = mysql_fetch_assoc($result);
$user = $row['ID'];

returing one value from the database using 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();

Categories