Problem
I am having a problem displaying the page after I compiled this code, but I cannot see what is wrong with it and I cannot debug due to it not appearing on the web.
PHP and PostgreSQL Code:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=***** user=***** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i"."".$searchq);
// Performing SQL query
$query = "SELECT * FROM enumbers WHERE code LIKE '%$searchq%'") or die ("could not search!");
$result = query($query);
if($result = 0){
$output = 'There is no such E-Number!'
}else{
while($row = mysql_fetch_array($query)) {
$code = $row['code'];
$name = $row['name'];
$type = $row['type'];
$vegan = $row['vegan'];
$output .= '<div> '.vegan.' ';
}
}
}
?>
The Form and Printing Code:
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
<?php
print("$output");
?>
</div>
Update
I think the problem might be I'm using some MySQL code, but I cannot tell If I am.
You are using mysql_fetch_array instead of postgres method. Please see the sample
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=****
dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
$output = '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// $searchq = preg_replace("#[^0-9a-z]#i"."".$searchq);
// Performing SQL query
$query = "SELECT * FROM enumbers WHERE code LIKE '%$searchq%'";
$ret = pg_query($dbconn, $query);
if(!$ret){
echo pg_last_error($dbconn);
exit;
}
$output = '';
while($row = pg_fetch_assoc($ret)){
$code = $row['code'];
print_r($row);
$name = $row['name'];
$type = $row['type'];
$vegan = $row['vegan'];
$output .= '<div> '.vegan.' ';
}
}
echo "Operation done successfully\n";
pg_close($dbconn);
?>
Related
I want to display the mobile number in mobileNo label but when I enter the employee id for search this code displays no result.
I want to display data using the while loop in my html form
search.php
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string(isset($_POST['search']));
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_row($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
{
$output = "No result";
}
}
?>
display.php
<html>
<head>
</head>
<body>
<form action="search.php" method="post">
<ul>
<li>
<label for="employeeId">Employee Id</label>
<input type="text" name="employeeId" placeholder="Employee Id" />
<input type="submit" value="search" name="search"/>
</li>
<li>
<label for="mobileNo">Mobile No.</label>
<?php echo $output;?>
</li>
</form>
</body>
</html>
1st : you missed else That's why $output variable alwasy overwrite by No result .
2nd : $search = $mysqli->real_escape_string(isset($_POST['search'])); this line wrong isset will return boolean value your escaping for boolean value .
3rd : Try to use prepared statement to avoid sql injection .
PHP:
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search=$_POST['search'];
$stmt = $conn->prepare("SELECT * FROM emp WHERE emp_id = ?");
$stmt->bind_param('i',$_POST['search']);
$stmt->execute();
$get_result = $stmt->get_result();
if($get_result->num_rows > 0)
{
while($rows = $get_result->fetch_assoc())
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}else //here else missed .
{
$output = "No result";
}
}
?>
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_assoc($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
else
{
$output = "No result";
}
}
?>
Problem
I would like to know how I would make the text at the top of the screen not show when connecting or searching the database. Below is a screenshot of what I am talking about.
Is it possible for it to not appear at all? Below is the code that connects to the database, as well as the code for the form below.
Code
The code to connect to the database:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=***** user=***** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// $searchq = preg_replace("#[^0-9a-z]#i"."".$searchq);
// Performing SQL query
$query = "SELECT vegan FROM enumbers WHERE code LIKE '%$searchq%'";
$ret = pg_query($dbconn, $query);
if(!$ret){
echo pg_last_error($dbconn);
exit;
}
$output = '';
while($row = pg_fetch_assoc($ret)){
$code = $row['code'];
print_r($row);
$name = $row['name'];
$type = $row['type'];
$vegan = $row['vegan'];
$output .= '<div> '.vegan.' ';
}
}
echo "Operation done successfully\n";
pg_close($dbconn);
?>
The code for the form:
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
<?php
print("$output");
?>
</div>
</div>
Just remove these two lines from your code
print_r($row);
.....
echo "Operation done successfully\n";
Try this one, Changes are noted via php comment (//)
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=***** user=***** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// $searchq = preg_replace("#[^0-9a-z]#i"."".$searchq);
// Performing SQL query
$query = "SELECT vegan FROM enumbers WHERE code LIKE '%$searchq%'";
$ret = pg_query($dbconn, $query);
if(!$ret){
echo pg_last_error($dbconn);
exit;
}
$output = '';
while($row = pg_fetch_assoc($ret)){
$code = $row['code'];
//Commented 1
//print_r($row);
$name = $row['name'];
$type = $row['type'];
$vegan = $row['vegan'];
$output .= '<div> '.vegan.' ';
}
}
//Commented 2
//echo "Operation done successfully\n";
pg_close($dbconn);
?>
I am creating an Invitation Card app for my upcoming event which will be held. My code successfully inserts the data into mysql database named booking having table name data. But there is problem with retrieving. When I fill the form and submit, it saves data in db but generates nothing. It gives following error:
Fatal error: Call to a member function query() on resource in C:\xampp\htdocs\booking\index.php on line 44
Here is my code, please tell me how to resolve this issue. I shall be very thankful to you.
<html>
<body>
<?php
if(isset($_POST['add'])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
$sql = "SELECT fname FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
$sql = "SELECT cnic FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
$sql = "SELECT address FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>
Change
$result = $conn->query($sql);
To
$result = mysql_query($sql);
For more info click here
I think you should be using mysql_query instead of $conn->query
I thin i spotted two errors in your code.
you should use
mysql_query($sql,$conn);
instead of (that was mentioned before)
$result = $conn->query($sql);
You missed a couple of opening php tags in your html table.
Try following code and let me know if it works.
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
<?php
$sql = "SELECT fname FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
<?php
$sql = "SELECT cnic FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
<?php
$sql = "SELECT address FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>
I'm running a simple database search against one table in my database. The results are then displayed in a table. If no results are found, the search shows a message that says "0 results", but sometimes it will echo the table headings without displaying any results. This search is part of a class project and isn't going to be an active database, so I haven't included any protection for SQL injection. Any help would be greatly appreciated.
<h2>Customer Search</h2>
<br>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<table class="hoverTable"><tr><th>Client</th><th>Address</th><th>City</th><th>State</th><th>Zip Code<br></th><th>Phone</th></tr>';
// We have results! Go fetch rows!
while ($row = mysqli_fetch_row($result)) {
// This loop runs until there are no more results left to echo
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row["Address"]. "</td><td> " . $row["City"]. "</td><td> " . $row["State"]. "</td><td> " . $row["ZipCode"]. "</td><td> " . $row["Phone"]. "</td></tr>";
}
echo "</table>";
}
} else {
// No results from query
$message = "0 results";
}
/* free result set */
mysqli_free_result($result);
}
}
?>
</div>
</div>
<div class="center">
<?php
if(isset($message)){ echo $message; }
?>
</div>
</body>
</html>
I find, and you may disagree, but properly indenting your code as you go and opening and closing tags before filling in content help reduce the number of problems. Having said that now it'll probably not work!
<html>
<head>
<title>db search</title>
</head>
<body>
<div>
<div>
<h2>Customer Search</h2>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
$conn = new mysqli( $servername, $username, $password, $dbname );
if ( $conn->connect_error ) die("Connection failed: " . $conn->connect_error );
if( isset( $_POST['search'] ) ) {
$searchq = $_POST['search'];
$searchq = preg_replace( "#[^0-9a-z]#i", "", $searchq );
$sql = "SELECT * FROM `Customers` WHERE `Client` LIKE '%$searchq%';";
if ( $result = mysqli_query( $conn, $sql ) ) {
if ( mysqli_num_rows( $result ) > 0 ) {
echo '
<table class="hoverTable">
<tr>
<th>Client</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Phone</th>
</tr>';
while( $row = $result->fetch_assoc() ) {
echo "
<tr>
<td>".$row["Client"]."</td>
<td>".$row["Address"]."</td>
<td>".$row["City"]."</td>
<td>".$row["State"]."</td>
<td>".$row["ZipCode"]."</td>
<td>".$row["Phone"]."</td>
</tr>";
}
echo '
</table>';
} else {
$message = "0 results";
}
}
mysqli_free_result( $result );
}
?>
</div>
</div>
<div class="center">
<?php if( isset( $message ) ){ echo $message; } ?>
</div>
</body>
</html>
Delete the redundant first while loop while ($row = mysqli_fetch_row($result)) {, if the query had just 1 result the first loop would have fetched it only while the 2nd while loop would have fetched nothing resulting in just a header and no body of the table.
<h2>Customer Search</h2>
<br>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<table class="hoverTable"><tr><th>Client</th><th>Address</th><th>City</th><th>State</th><th>Zip Code<br></th><th>Phone</th></tr>';
// We have results! Go fetch rows!
// This loop runs until there are no more results left to echo
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row["Address"]. "</td><td> " . $row["City"]. "</td><td> " . $row["State"]. "</td><td> " . $row["ZipCode"]. "</td><td> " . $row["Phone"]. "</td></tr>";
}
echo "</table>";
} else {
// No results from query
$message = "0 results";
}
/* free result set */
mysqli_free_result($result);
}
}
?>
</div>
</div>
<div class="center">
<?php
if(isset($message)){ echo $message; }
?>
</div>
</body>
</html>
I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>