I have modified my mysql table from InnoDB to MyISAM and then i have added FULLTEXT using this sentence :
ALTER TABLE personal ADD FULLTEXT(personal_name,surname,initials,email,telephone,adegree);
In my application, i have 6 input fields like these:
- id
-personal_name
-surname
-initials
-email
-telephone
and 1 select field like this:
-adegree
As you know , i have to retrieve information acording these fields, so how i can to do using MATCH/AGAINST ? , if not is possible using MATCH/AGAINS for a multiple search, i'm available to implement any other way.
I have used the %LIKE% sentence, but it doesn't work good, here is the code:
file: searchUser.php
$(document).ready(function(){
$("#search").on("click",function(e){
e.preventDefault();
$.ajax({
dataType:'html',
type: "POST",
url: "processarSearchUser.php",
data: dades ,
success: function(data){
$("#contenidor").show("500",function(){
$("#contenidor").html(data);
})
}//succes
});//ajax
});//search
});//document
<form name="formulariFilter" id="formulariFilter" method="post" enctype="multipart/form-data">
<h1>Search User</h1>
<tr>
<td><b>id:</b></td>
<td><input type="text" name="id" id="id"></td>
</tr>
<tr>
<td><b>Personal name:</b></td>
<td><input type="text" name="personalname" id="personalname" ></td>
</tr>
<tr>
<td><b>Surname:</b></td>
<td><input type="text" name="surname" id="surname" ></td>
</tr>
<tr>
<td><b>Initials:</b></td>
<td><input type="text" name="initials" id="initials" ></td>
</tr>
<tr>
<td><b>Email:</b></td>
<td><input type="text" name="email" id="email" ></td>
</tr>
<tr>
<td><b>Telephone:</b></td>
<td><input type="text" name="telephone" id="telephone" ></td>
</tr>
<tr>
<td><b>Academic degree:</b></td>
<td><select name="adegree" id="adegree">
<option value="0">---Select something---</option>
<?php
$consulta= mysqli_query($conexio, "SELECT adegree from personal" );
while($fila=mysqli_fetch_assoc($consulta)){
echo"<option value='".$fila['adegree']."'/>"."<b>".$fila['adegree']."</b>"."</option>";
}
?>
</select></td>
<!--<td><input type="text" name="adegree" id="adegree" ></td>-->
</tr>
<tr>
<td colspan="2" id="td_boto"><input type="button" name="search" id="search" value="SEARCH" ></td>
</tr>
</form>
file : processarSearchUser.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
include("../Projecte Bonita/conectar.php");
$conexio=conectar_bd();
$id = mysqli_real_escape_string($conexio,addslashes($_POST['id']));
$personalname = mysqli_real_escape_string($conexio,addslashes($_POST['personalname']));
$surname = mysqli_real_escape_string($conexio,addslashes($_POST['surname']));
$initials = mysqli_real_escape_string($conexio,addslashes($_POST['initials']));
$email = mysqli_real_escape_string($conexio,addslashes($_POST['email']));
$telephone = mysqli_real_escape_string($conexio,addslashes($_POST['telephone']));
$adegree = mysqli_real_escape_string($conexio,addslashes($_POST['adegree']));
/*$sql="SELECT applus_code,personal_name,surname,initials,email,telephone,adegree from personal WHERE
id LIKE '%".$id."%' or
personal_name LIKE '%".$personalname."%' or
surname LIKE '%".$surname."%' or
initials LIKE '%".$initials."%' or
email LIKE '%".$email."%' or
telephone LIKE '%".$telephone."%' or
adegree LIKE '%".$adegree."%'";*/
if($adegree != 0){
$sql="SELECT * from personal WHERE
id LIKE '%".$id."%' and
personal_name LIKE '%%' and
surname LIKE '%".$surname."%' and
initials LIKE '%".$initials."%' and
email LIKE '%".$email."%' and
telephone LIKE '%".$telephone."%' and
adegree LIKE '%".$adegree."%'";
}
else{
$sql="SELECT * from personal WHERE
id LIKE '%".$id."%' and
personal_name LIKE '%%' and
surname LIKE '%".$surname."%' and
initials LIKE '%".$initials."%' and
email LIKE '%".$email."%' and
telephone LIKE '%".$telephone."%' ";
}
$consulta= mysqli_query($conexio,$sql);
$resultat=mysqli_fetch_assoc($consulta);
if($consulta){
if(mysqli_num_rows($consulta) >0){
if(!empty($resultat)){
echo "<table id='reultat' class='taula'>";
echo"<thead>";
echo "<tr>";
echo"<th>id</th>";
echo"<th>Personal name</th>";
echo"<th>Surname</th>";
echo"<th>Initials</th>";
echo"<th>Email</th>";
echo"<th>Telephone</th>";
echo"<th>Adegree</th>";
echo"</tr>";
echo"</thead>";
echo"<tbody";
while($fila=mysqli_fetch_assoc($consulta)){
echo"<tr>";
echo "<td>".$fila['id']."</td>";
echo "<td>".$fila['personal_name']."</td>";
echo "<td>".$fila['surname']."</td>";
echo "<td>".$fila['initials']."</td>";
echo "<td>".$fila['email']."</td>";
echo "<td>".$fila['telephone']."</td>";
echo "<td>".$fila['adegree']."</td>";
echo"</tr>";
}
echo "</tbody>";
echo "<table>";
liberar($consulta);
desconectar_bd($conexio);
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>No results!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>No results!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>Query error!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"no post";
}
?>
I recently added a search feature to one of my websites using the LIKE function.
When I submit my search form via GET, I build the database query string based on those variables that are passed with the form.
if(strcmp($_GET['SSeries'],'') != 0) {
$searchString .= "Series LIKE '%".$_GET['SSeries']."%' AND ";
$uFriend .= "Series CONTAINS '".$_GET['SSeries']."' AND ";
}
if(strcmp($_GET['SModel'],'') != 0) {
$searchString .= "Model LIKE '%".$_GET['SModel']."%' AND ";
$uFriend .= "Model CONTAINS '".$_GET['SModel']."' AND ";
}
if(strcmp($_GET['SSerial'],'') != 0) {
$searchString .= "Serial LIKE '%".$_GET['SSerial']."%' AND ";
$uFriend .= "Serial CONTAINS '".$_GET['SSerial']."' AND ";
}
$_SESSION['searchString'] = $searchString;
then at the end, declare a variable that connects them all together.
Then, I just use that variable in my search string like so:
if(empty($_SESSION['searchString'])) {
$sql = "SELECT * from identification;";
$sqluFriend = "Search ALL";
} else {
$sql = "SELECT * from identification WHERE ".substr($_SESSION['searchString'], 0, -5).";";
$sqluFriend = "Search ".substr($_SESSION['uFriend'], 0, -5)."";
}
If the search string is empty, I create a query that has no where clause.
Also, note the use of the substr() method used, as removes the last 5 symbols from the search string (Basically so the string doesn't end with AND as that would cause issues with the query.) Also, you can ignore the $sqluFriend variables, I use those to display a user friendly version of the query.
Basically, as shown above, I build the search string depending on if the GET variable is posted, it makes it a dynamic search query.
Another thing is you should wrap your $searchString builder with if statements that check if any of the data is posted, to avoid errors/return error codes etc. Here is how I did that:
if((isSet($_GET['SSSeries']))
|| (isSet($_GET['SSModel']))
|| (isSet($_GET['SSSerial']))) {
You can of course expand this to meet your needs fairly easily.
What I did was connected my form to an ajax request every time an input was changed, so that when someone entered anything it would automatically reload the table with the results.
Hope I could help.
Related
I'm trying to delete a row in an SQL database by an id. I have found questions here related to this but nothing seems to work, perhaps because my page is populated (dynamically?) based on selecting a variable. The rows are displayed on my page based on a dropdown (locationlab) and I have a delete button after each row. It looks like this.
I have the Id displayed temporarily at the end of the row just be sure that the code sees the variable (& it does!).
The code to populate the page looks like this:
<?php
$locationlab = $_POST[locationlab];
$sql = "SELECT * FROM lab WHERE locationlab LIKE '{$locationlab}'";
echo($locationlab);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo'
<table>
<form action=testpage2.php method=post>
<td width="10%"><input type=text name=make value='. $row["make"].'></td>
<td width="10%"><input type=text name=model value='. $row["model"].'></td>
<td width="20%"><input type=text name=hostname value='. $row["hostname"].'></td>
<td width="15%"><input type=text name=ipaddress value='. $row["ipaddress"].'></td>
<td width="20%"><input type=text name=ipmiipaddress value='. $row["ipmiipaddress"].'></td>
<td width="15%"><input type=text name=terminalserveraddress value='. $row["terminalserveraddress"].'></td>
<td width="10%"><input type=text name=locationlab value='. $row["locationlab"].'></td>
<td><input type=submit name=update value=update></td>
<td><input type=submit name=delete value=delete></td>
<td id=id name=id value='. $row["id"].'>'. $row["id"].'</td>
</table>
</form>';
}}
?>
I can input the SQL query below manually in the phpMyAdmin page so I know it is correct.
The code for the Delete button looks like this:
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE * FROM lab WHERE ='$_POST[id]'");
mysql_query($deletequery, $conn);
};
?>
When I click the delete button it appears to refresh the page but nothing changes. I imagine that if I can get the delete button working, the update will work in a similar fashion but for now I'm stumped.
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE FROM lab WHERE **columnName** ='$_POST[id]'");
mysql_query($deletequery, $conn);
}
?>
You are missing column name in query. Also there is no * in DELETE statement, because deleting means deleting row.
First of all let me help you in formatting the code
you should not write entire HTML code in echo...
instead try this one....
<?php
while($row = $result->fetch_assoc()) {
?>
<table>
<form action="testpage2.php" method="pos">
<td width="10%"><input type="text" name="make" value="<?= $row["make"] ?>"></td>
....
....
</table>
</form>
<?php
}
?>
also you should use mysqli instead of mysql
and your database query is also incorrect, it must be like this..
DELETE FROM lab WHERE id ='$_POST[id]'
if you use mysqli then you can also use some functions like this..
mysqli_query($con,$deletequery)
if(mysqli_errno($con))
{
echo("SOme error while executing query : ".mysqli_error($con));
}
I'm trying to make a log of cars going in and out of a parking lot.
The car info is retrieved from a database and is working fine. The problem I'm having is getting the in/out times to store into the database. In a previous page I had done it so that the form was separate from the table and the input info would be updated but for this page I need to have a dynamic amount of fields varying on the cars in the database. I am not sure what I am doing wrong but here is my code, the data is not being sent or stored in the data base.
<h3>Update Car</h3>
<form action="carLog.php" method="post">
<fieldset>
<legend>Car Log</legend>
<?php //This prints out the car log data
$sql = "SELECT * FROM carLog";
$result = $databaseConnection->query($sql);
echo "<table class='TFtable' border='1' style='width':100%>"; //starts the table tag
echo "<tr>
<td>Name</td>
<td>Vehicle</td>
<td>Licence Plate</td>
<td>In</td>
<td>Out</td>
<td>In</td>
<td>Out</td>
<td>Comments</td>
</tr>"; //sets headings
while($row = $result->fetch_assoc()) { //loops for each result
echo "<tr>
<td>".$row['name']."</td>
<td>".$row['vehicle']."</td>
<td>".$row['plate']. "</td>
<td><input type='text' size='5' maxlength='5' name='inTime' value='".$row['inTime']."' id='inTime' /></td>
<td><input type='text' name='outTime' value='".$row['outTime']."' id='outTime' /></td>
<td><input type='text' name='inTime2' value='".$row['inTime2']."' id='inTime2' /></td>
<td><input type='text' name='outTime2' value='".$row['outTime2']."' id='outTime2' /></td>
<td><input type='text' name='comments' value='".$row['comments']."' id='comments' /></td>
</tr>";
}
echo "</table>"; //closes the table
?>
<input type="submit" name="Save" value="Save" />
</fieldset>
</form>
The database connection is fine and working. Here is the php that handles the post:
if (isset($_POST['Save'])){
$name = $_POST['name'];
$vehicle = $_POST['car'];
$plate = $_POST['plate'];
$inTime = $_POST['inTime'];
$outTime = $_POST['outTime'];
$inTime2 = $_POST['inTime2'];
$outTime2 = $_POST['outTime2'];
$comments = $_POST['comments'];
$query = "UPDATE carLog SET inTime = '$inTime', outTime = '$outTime', inTime2 = '$inTime2', outTime2 = '$outTime2' WHERE plate = '$plate'";
$databaseConnection->query($query);
Note:
You only have five (5) input fields inside your while() loop, but you are trying to process eight (8) input fields in your carLog.php. So it will return undefine variables error.
Pass the input fields in array.
Inside the loop, hide the primary id of each car/vehicle in a hidden input (also in array).
Add this inside your while() loop:
/* ASSUMING vehicle_id IS THE PRIMARY ID OF YOUR carLog TABLE; JUST REPLACE IT WITH THE RIGHT COLUMN NAME */
echo '<input type="hidden" name="hidden_id[]" value="'.$row["vehicle_id"].'">';
You have to add [] in your input's name tags.
<td><input type='text' name='outTime[]' .....
Do it to the rest of your inputs.
Then on your carLog.php file, which process the input (at least use
*_real_escape_string to prevent SQL injections). We will be checking each input using for() loop:
if (isset($_POST['Save'])){
for($x = 0; $x< count($_POST["hidden_id"]); $x++){
$vehicleid = $databaseConnection->real_escape_string($_POST['hidden_id'][$x]);
$inTime = $databaseConnection->real_escape_string($_POST['inTime'][$x]);
$outTime = $databaseConnection->real_escape_string($_POST['outTime'][$x]);
$inTime2 = $databaseConnection->real_escape_string($_POST['inTime2'][$x]);
$outTime2 = $databaseConnection->real_escape_string($_POST['outTime2'][$x]);
$comments = $databaseConnection->real_escape_string($_POST['comments'][$x]);
$query = "UPDATE carLog SET inTime = '$inTime', outTime = '$outTime', inTime2 = '$inTime2', outTime2 = '$outTime2' WHERE vehicle_id = '$vehicleid'";
$databaseConnection->query($query);
} /* END OF FOR LOOP */
} /* END OF ISSET Save */
Since you are using mysqli_* already, consider using the prepared statement approach.
Scenario:
The user inputs the reference number and based on his reference number, I should display the location equivalent to it.
SQL:
require_once('conn.php');
$refnum = (isset($_POST['refOff'])) ; //Get filename set in form
$query = mysql_query("SELECT * FROM pilot WHERE geo=$refnum");
// display query results
while($row = mysql_fetch_array($query))
{
$rname =$row['rname'];
$pname =$row['pname'];
$mname =$row['mname'];
}
HTML:
<tr>
<td width="283" height="32">Region:</span> </td>
<td width="407"> <input type="text"value="<?php echo $rname;?>"/></td>
</tr>
<tr>
<td width="283" height="32">Province:</span> </td>
<td width="407"> <input type="text"value="<?php echo $pname;?>"/></td>
</tr>
<tr>
<td width="283" height="32">City:</span> </td>
<td width="407"> <input type="text"value="<?php echo $mname;?>"/></td>
</tr>
The PROBLEM:
Errors are being displayed saying the rname,pname,and mname are undefined. What is wrong?Thanks again
First of all I'm believing that you have an input element of this sort in your html:
<label for='refOff'>Reference Number: </label>
<input type='text' id='refOff' name='refOff'/>
This line in your code:
$refnum = (isset($_POST['refOff']))
only returns a boolean value (i.e. true or false) and never returns the actual value the user has entered into the 'refOff' html input element. This should rather work well using the ternary operator:
$refnum = (isset($_POST['refOff']))? $_POST['refOff'] : null;
if($refnum){
$query = mysql_query("SELECT * FROM pilot WHERE geo=$refnum");
// display query results
while($row = mysql_fetch_array($query))
{
$rname =$row['rname'];
$pname =$row['pname'];
$mname =$row['mname'];
}
}
Goodluck!
I have a PHP script that connects to a MySQL database using the mysqli extension to search for Blog Posts based on Username or ID. I created a VIEW called BlogSearch that uses joins form other tables to aggregate the information I need together that is represented like this:
The Tables it pulls from are called Profiles that has the User information, BlogPosts and BlogCategory
Everytime I search I get the error:
Unknown column 'chenzhen' in 'where clause'
The PHP code I'm using below:
require 'database.php';
$query = "SELECT * FROM BlogSearch";
echo <<<EOF
<form method='post' action='' style="padding: 30px 0;">
<table cellspacing="0" border="0" style="float: left;">
<tr>
<td>Search Blog Posts by Username/ID</td>
<td><input type="text" id="search" name="search" style="width: 300px;"/></td>
<td><input type="submit" id="submit_button" value="Search" name="submit_button" style="float: right;" /></td>
</tr>
</table>
</form>
EOF;
if(isset($_POST['submit_button']))
{
$search_term = $_POST['search'];
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
// run the query and store the results in the $result variable.
$result = $mysqli->query($query) or die(mysqli_error($mysqli));
}
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' style='clear: both;'>";
echo "<table cellspacing='0' cellpadding='15'>
<th width='5%'>
<input type='checkbox' id='allcb' onclick='checkAll(this)' name='allcb' />Check All
</th>
<th width='10%'>User</th>
<th width='85%'>Blog Post Title</th>
";
while ($row = $result->fetch_object()) {
$title = substr($row->PostCaption,0,50);
$id = $row->PostID;
$user = $row->NickName;
//put each record into a new table row with a checkbox
echo "<tr>
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td>$user</td>
<td>$title</td>
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}
I don't know why it's even identify the username as a column. Can anyone point me in the right direction to fix this?
Thanks in advance.
Any element in an SQL query that isn't an SQL keyword or a literal (denoted by single quotes), is assumed to be an object (e.g. table, column) name.
Your problem is the missing quotes around $search_term in your WHERE clause:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
You should add them, as thus:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = '$search_term' ";
Enclose your $search_term in single quotes in where clause like this '$search_term'
This is the page that uses this code.I have a php page which extracts data from a dbms which contains email address. This works. It then displays the email address and other stored dbms data. The user then has the option of putting an "X" in a field designed in the php page called emailselected. This also works. I now want to update the dbms with the new field based on the stored email address but the update statement doesn't work. Please help. The code is listed here:
include("db.php");
if (isset($_POST['ssubmit']))
{
$id_save = $test['id'];
$emailselected_save = $_POST['emailselected'];
$email_save = $test['email'];
$rc = mysql_query("UPDATE emails SET selected='$emailselected_save' WHERE id = 'id'");
if (!$result) {
die('What?: ' . mysql_error());
}
$num = mysql_affected_rows();
printf("Updated %d rows\n", $num);
echo "<input type='button' value='Email(s) sent' onclick='goBack()' />";
mysql_close($conn);
} else {echo "hello";}
?>
<form method='post'>
<div id='headd'>
<br />
<input type='button' value='Close this window without Sending' onclick='goBack()' />
<input type='submit' name='ssubmit' id='ssubmit' value='Send Email Now!!!' />
<p>Place an "X" in the emails you wish to send!!!</p>
</div>
<br /><br/>
<?php
include("db.php");
$result = mysql_query("SELECT * FROM emails WHERE unsubscribe != 'x' ORDER BY lastname ASC");
while($test = mysql_fetch_array($result))
{
?>
<table border='1' width='78%'>
<tr align=\"left\">
<td width='4%'><font color='black'><input type='text' size='1' id='emailselected' name='emailselected' /></font></td>
<td width='15%'><font color='black'><?php echo $test['lastname']?></font></td>
<td width='15%'><font color='black'><?php echo $test['firstname']?></font></td>
<td width='40%'><font color='black'><?php echo $test['email']?></font></td>
<td width='4%'><font color='black'><?php echo $test['id']?></font></td>
</tr>
</table>
<?php
}
?>
</form>
Error is:
$rc = mysql_query("UPDATE emails SET selected='$emailselected_save' WHERE id = 'id'");
Should be:
$rc = mysql_query("UPDATE emails SET selected='$emailselected_save' WHERE id = '$id_save'");
Your code is vulnerable for SQL injection. So you should filter your data. But I would just switch to PDO and use prepared statements.
http://php.net/manual/en/pdo.prepare.php