mysql database search by columns - php

I'm new to mysql and php. I'm working on songs database. I have a search script which searches all columns of my database and it shows results in a table. But I want to make that search script to search by selected column field. Below the search box I want to add bullet options (ex: search by column 1, column 2, column 3, column 4) You can see a pic below.
Songs database table.
+----+--------+----------+-----+-------+
| id | title | artist | key | genre |
+----+--------+----------+-----+-------+
| 1 | xxxxx | xxx xxxxx| xxx | xxxxx |
| 2 | xxxxx | xxx xxxxx| xxx | xxxxx |
| 3 | xxxxx | xxx xxxxx| xxx | xxxxx |
| 4 | xxxxx | xxx xxxxx| xxx | xxxxx |
| 5 | xxxxx | xxx xxxxx| xxx | xxxxx |
+----+--------+----------+-----+-------+
Search script :
<?php
$host = "localhost";
$user = "xxxxxxx";
$password = "xxxxxxx";
$database_name = "xxxxxx";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$pdo->exec("set names utf8");
$search=$_POST['search'];
$query = $pdo->prepare("select * from table where title LIKE '%$search%' OR key LIKE '%$search%' OR genre LIKE '%$search%' OR artist LIKE '%$search%' LIMIT 0 , 100");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
$row_cnt = $result->num_rows;
printf("<p class='notice'>Your search for <span class='blue'>“</span><span class='blue'>" . $result['search'] . "</span><span class='blue'>”</span> yielded %d results.\n</p>", $row_cnt);
echo "<table class='table'>";
echo "<tr class='tablehead'>";
echo "<th>Title</th>";
echo "<th>Artist</th>";
echo "<th>Key</th>";
echo "<th>Genre</th>";
echo "</tr>";
while ($results = $query->fetch()) {
echo "<tr>";
echo "<td> " " " . $results['title'] . " </td>";
echo "<td>" . $results['artist'] . "</td>";
echo "<td>" . $results['key'] . "</td>";
echo "<td>" . $results['genre'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
Im newbie. Please help.
UPDATE
$search=$_POST['search'];
$field=$_POST['radio_grp'];
switch($field)
{
case 'Title' : $field='title';
break;
case 'Artist' : $field='artist';
break;
case 'Category' : $field='category';
break;
}
$query = $pdo->prepare("select * from lyrics_a where $field LIKE '%$search%' LIMIT 0 , 100");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
echo"<form action='search.php' method='post'>
Search: <input type='text' id='search' name='search' placeholder='Search' required data-validation-required-message='Please enter atleast 3 characters'/>
<input type='submit' class='searchButton greenButton' value='Go' />
<input type='radio' name='search' value='title'/>Title
<input type='radio' name='search' value='artist'/>Artist
<input type='radio' name='search' value='category'/>Category
</form><br>";
// Display search result
if (!$query->rowCount() == 0) {
$row_cnt = $result->num_rows;
echo "<table class='table'>";
echo "<tr class='tablehead'>";
echo "<th>Title</th>";
echo "<th>Artist</th>";
echo "<th>Category</th>";
echo "</tr>";
while ($results = $query->fetch()) {
echo "<tr>";
echo "<td> " . $results['tel_title'] . " " . $results['title'] . " </td>";
echo "<td>" . $results['artist'] . "</td>";
echo "<td>" . $results['category'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>

You should get values of your radio buttons and make appropriate query
$search=$_POST['search'];
$field=$_POST['radio_grp'];
switch($field)
{
case 'Title' : $filed='title' // or your column field
break;
//---similar cases
}
$query = $pdo->prepare("select * from table where $field LIKE '%$search%' LIMIT 0 , 100");

Try this code
Set the value of radio button same as column name
<input type="radio" name="search_by" value="title">title<br>
<input type="radio" name="search_by" value="artist">artist<br>
<input type="radio" name="search_by" value="key">key<br>
<input type="radio" name="search_by" value="genre">genre<br>
$search=$_POST['search'];
$search_by=$_POST['search_by'];
$query = $pdo->prepare("select * from table where $search_by LIKE '%$search%' LIMIT 0 , 100");

Related

PHP SQL integration

I am connected to my database.
Created a drop down-box. Which works fine:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Now I am stuck trying to put the values from table Customer into an array
Which looks like this:
$types = array (
'A' => 10.99,
'B' => 4.99,
'C' => 13.99);
What I intend to do is to create this array where,
Instead of A B C, there are CustomeName and CustomerPrice in place of the price.
The Customer table has
+----------------+-----------------+---------------+
| Customer_ID | CustomerName | CustomerPrice |
+----------------+-----------------+---------------+
| 1 | A | 10.99 |
| 2 | B | 4.99 |
| 3 | C | 13.99 |
+----------------+-----------------+---------------+
Please help
You basically do the same thing you did with the drop down except to generate the array. You could do it in the same loop:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
$array = array();
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
$array[$row['CustomerName']] = $row['CustomerPrice'];
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Hope this helps

PHP : show all rows in MySQL that contain the same value in a column

I am trying write code in PHP with a Mysql database, and the problem is I want to show all rows with a same column value. for example like this:
id | Name | age | Location | type
----+----------+-----+----------+------
1 | Ane | 22 | SG | 1
2 | Angi | 19 | IND | 2
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
6 | Mikha | 25 | JP | 2
I want only show the rows with value in column type = 1 or value in column Location and showing as table in html view.
The result what I want is like this:
id | Name | age | Location | type
---+----------+-----+----------+------
1 | Ane | 22 | SG | 1
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
This is my code:
<?php
$con = mysqli_connect("localhost","root","","testuser");
$query = mysqli_query("SELECT * FROM `usersdata` WHERE `type`='1'");
$result = mysqli_query($con,$query);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
But I got errors like this:
Warning: mysqli_query() expects at least 2 parameters, 1 given in www.myweb.com\users_list\type.php on line 94 << this point "$query" line
Warning: mysqli_query(): Empty query in www.myweb.com\users_list\type.php on line 95 << this point "$result" line
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in www.myweb.com\users_list\type.php on line 109 << this point "while ($row=" line
I was trying understand and still i don't get it, anyone can help me please?! thanks.
Change
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
to
$query = "SELECT * FROM usersdata WHERE type='1'";
EDIT
Just for explanation:
mysqli_query takes 2 arguments: connection and query. I assumed that you wanted to just create query string in this line where this error arouse since it is used one line furter as a query string.
Issue is in bolow lines.
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
$result = mysqli_query($con,$query);
You have 2 ways to resolve this.
1. $query = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($con,$query);
2. $query = mysqli_query($con,"SELECT * FROM `usersdata` WHERE `type`='1'");
Try this one. It should be working fine
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($conn, $sql);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>

How do I update a row in the database with the data from website?

I am trying to assigned each student with a company from a drop down list and have it updated in the database under the correct student.
So basically, this is how my website looks like.
___________________________________________________________________
| Student ID | Admin No | Student Name | Company List |
| 1 | 1234 | ABC | <drop down list> |
| 2 | 2345 | BCD | <drop down list> |
| 3 | 3456 | CDE | <drop down list> |
| 4 | 4567 | DEF | <drop down list> |
And this is the codes for the table above.
<form name="IT" action="getIT_now.php" method="post">
<table cellspacing="0">
<tr>
<th>Student ID</th>
<th>Admin Number</th>
<th>Student Name</th>
<th>GPA</th>
<th>Gender</th>
<th>Company List</th>
</tr>
<?php
$con=mysqli_connect("....","....","....",".....");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create the query
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$studentid = $row['student_id'];
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo "<td>" . $studentid . "</td>";
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' onclick='if(this.value != '') { myform.submit(); }'>".$options."</select></td>";
}
echo "</tr>";
?>
</table>
<input type='submit' value='Submit Pick' />
</form>
Now this form will actually go to another page since I have include a form action.
So the codes in this getIT_now.php page is
<?
$con=mysqli_connect("...","....","....","....");
if (!$con)
{
die('Could not connect: ' . mysqli_errno());
}
$ddlvalues = $_POST['ddl'];
$studentid = $_POST['student_id'];
$query = mysqli_query($con, "INSERT INTO student_details(company) VALUES('" . $ddlvalues . "');");
?>
However, when I check the database, only the first option in the drop down list is reflected in a new row. I have tried to use the UPDATE query statement, but it is wrong.
This is the query for the UPDATE statement.
UPDATE student_details SET company = '" . $ddlvalues . "' WHERE student_id = '" . $studentid . "';
The problem I'm having right now is actually:
How do I make Student ID on the website and in the database to match so that it can update correctly?
Why is it that only the first option in the drop down list is reflected when I use the INSERT query?
I am quite new to PHP so I am really struggling with this.
You don't have an input that holds the student_id, i.e $_POST['student_id'] is not set, also you would have to validate the user inputs before you pass them to query, You can use prepared statements,
Try with a hidden field like
echo '<input type="hidden" name="student_id" value="'.$studentid.'"/>';

can only get one value for $row['id']

I'm trying to get all the records in my database and it was successful, however I can only get 1 id value. I need to get all the id in my database and call a javascript function. In my code I can only get the id of the last record. How can I get them all?
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("database_name");
$query = "SELECT * FROM news ORDER BY date DESC LIMIT 0 , 3";
$result = mysql_query($query);
echo "<table>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>" . $row['header'] . "</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
echo "<tr>";
$position=0;
$message= $row['desc'];
$post = substr($message,$position,300);
echo "<td>" . $post . "...</td>";
echo "</tr>";
echo "<tr>";
$id = $row['id'];
echo "<tr><td>";
/*The start of chaos */
echo "<form action='' method='post' onSubmit='ReadMore()'>";
for($ctr=1;$ctr<=3;$ctr++){
$id=$ctr; //This should change and increment the value of id, isn't it?
echo "<input type='hidden' name='more' value=".$id." id='more'/>";
}
echo "<input type='submit' name='read' value='Read More'>
</form>
</td></tr>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
What's happening here is that it will display records from the database: $row['header'], $row['date'], $row['desc'] then a button which says Read More in a loop. What I would like to happen is to call a function after clicking 'read more', depending on the id.
For example,
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 3
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 2
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 1
___________________________
Is that possible? or am I missing something. My code only displays $id=1 for all the buttons. I'm sorry for this.
you may try like this
make the id field name as array like more[] and bring the form out side loop as shown
no need of for loop there to get the ids u already using while loop
bring submit button also outside loop
if u want to show the details of that post then why again u using form u can simply link it to the details page n can pass the id no need to submit it as a form .
check the code below
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("database_name");
$query = "SELECT * FROM news ORDER BY date DESC LIMIT 0 , 3";
$result = mysql_query($query);
//echo "<form action='' method='post' onSubmit='ReadMore()'>";
echo "<table>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>" . $row['header'] . "</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
echo "<tr>";
$position=0;
$message= $row['desc'];
$post = substr($message,$position,300);
echo "<td>" . $post . "...</td>";
echo "</tr>";
echo "<tr>";
$id = $row['id'];
echo "<tr><td>";
/*The start of chaos */
//for($ctr=1;$ctr<=3;$ctr++){
//$id=$ctr; //This should change and increment the value of id, isn't it?
//echo "<input type='hidden' name='more[]' value=".$id." id='more[]'/>";
//}
echo "<tr><td><a href='post_details.php?post_id=".$id."'>Read More</a></td></tr>";
</td></tr>";
echo "</tr>";
}
echo "</table>";
//echo "</form>";
mysql_close($con);
?>

PHP is printing an empty column from MySQL even though it is not empty

I am printing a 3 column MySQL table on a webpage. Everything prints out except for the second column, its just blank.
Here is the code I'm using:
$connection = mysql_connect($hostname, $username, $password);
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("MEASURE", $connection);
$numberz = 54;
mysql_query("INSERT INTO measurement (DATA)
VALUES
('$numberz')");
$result = mysql_query("SELECT * FROM measurement");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>DATA</th>
<th>TIME</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['TIME'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($connection);
This is what I get on my webpage:
ID DATA TIME
1 2013-02-26 14:32:26
2 2013-02-26 14:32:26
3 2013-02-26 14:32:27
Notice how the second column is blank
Here's how the table looks in MySQL:
ID | data | TIME
| 1 | 1 | 2013-02-26 14:32:26 |
| 2 | 1 | 2013-02-26 14:32:26 |
| 3 | 1 | 2013-02-26 14:32:27 |
Where you are printing out to the page you are accessing $row['DATE'] which looks like it should be $row['DATA']
try this:
if you table field name are ID, data, TIME. you are using capital and wrong field name.
$result = mysql_query("SELECT * FROM measurement");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>DATA</th>
<th>TIME</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['data'] . "</td>";
echo "<td>" . $row['TIME'] . "</td>";
echo "</tr>";
}
echo "</table>";
Hope this will work.

Categories