MySQL, while Loop & comparison with in_array - php

here is the code:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if (in_array($array['ipsum'], $page1)) {echo "<h2>correct</h2>"; break;}
else {echo "<h2>not correct</h2>";} }
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";
I have a table with 2 rows in the database: first one is lorem the second one is ipsum (both are INT).
The table is manually compiled when it is needed.
What I want to do is to get the second row (ipsum) and create an array. I don't need to echo values of the array, but I need to compare it with a variable ($page1. this variable is a integer number and it changes continuously).
How could I fix it?

I think this should do what you are after. You should look into switching from the mysql functions/driver to the mysqli or PDO drivers.
<?php
$page1 = (int)$page1;//force $page1 to be an int to avoid SQL injections
$sql = "SELECT * FROM example where ipsum = " . $page1;
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
echo "<h2>correct</h2>";
} else {
echo "<h2>not correct</h2>";}
}
echo '<div id="nucleo">
<h3>lorem ipsum</h3>
<h1>' . $page1 . '</h1>';
http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
http://php.net/manual/en/function.mysql-num-rows.php

You are using in_array() to compare two integer values. you should simply use the === operator like so:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if ($array['ipsum'] === $page1) {
echo "<h2>correct</h2>";
break;
} else {
echo "<h2>not correct</h2>";
}
}
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";

I fixed it this way:
$array = array();
while ($row = mysql_fetch_array($query)) {
array_push($array, $row["ipsum"]);
}
if (in_array($page1, $array)) {echo "correct";}
else {echo "not correct"; }
I realized by using print_r that the array was not really how I though it was. This way above use all the row of a colums to compose the array... array([0] => row1 [1] => row2 and so on.
Thanks everyone for the help...I apologize for not being very clear about my problem.

Related

php mysql search continues forever

I'm trying to create a basic "search my table columns for all rows that match, and show me the rows" type search. What I ended up with is a query that repeats forever, and the resulting webpage never stops loading. Classic example of a loop that can't end. I don't know why though. I'm trying to keep each little step in it's own function like a good boy, and reusing functions.
A person should be able to search for question or john to return one row, plus or minus looks like two rows, and test will return three rows.
Please help!
function databaseconnection($sql){
$usernm="XXXfooXXX";
$passwd="XXXfooXXX";
$host="XXXfooXXX";
$database="contact_info";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$result = mysql_query ($sql) or die (mysql_error ());
return $result;
}
function searchtable(){
echo 'searchtable() <br />';
if ($_POST['search'] != "" ){
$search = preg_replace('/[^ \wa-zA-Z0-9_.#()\-+~,?]+/', '', $_POST['search']);
}
if ($search){
$sql = "SELECT * FROM names_numbers WHERE name LIKE \"%{$search}%\"".
" OR phone_address LIKE \"%{$search}%\"".
" OR notes LIKE \"%{$search}%\"";
echo 'attempting sql action<br />';
echo "$sql <br />";
while ($row = mysql_fetch_assoc(databaseconnection($sql))){
print_r($row);
}
}
}
function draw_search_form(){
echo '<form action="./numbers.php" method="post">'."\n";
echo 'notes:<br>'."\n";
echo '<input type="text" name="search"><br>'."\n";
echo '<input type="submit" value="Submit">'."\n";
echo '</form>'."\n";
}
I believe in your while loop, you are executing the query every time, which resets your result iterator. When you switch to mysqli or PDO you can refactor to run the query once, then iterate over the results.
$results = databaseconnection($sql);
while($row = mysqli_fetch_assoc($results) {
...
}
With your current while loop, you are opening a new database connection, running the query and getting the first row again and again.
This can be easily fixed by moving your query out of database, and then iterating over the result
Here is the code with changes
function databaseconnection($sql){
$usernm="XXXfooXXX";
$passwd="XXXfooXXX";
$host="XXXfooXXX";
$database="contact_info";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$result = mysql_query ($sql) or die (mysql_error ());
return $result;
}
function searchtable(){
echo 'searchtable() <br />';
if ($_POST['search'] != "" ){
$search = preg_replace('/[^ \wa-zA-Z0-9_.#()\-+~,?]+/', '', $_POST['search']);
}
if ($search){
$sql = "SELECT * FROM names_numbers WHERE name LIKE \"%{$search}%\"".
" OR phone_address LIKE \"%{$search}%\"".
" OR notes LIKE \"%{$search}%\"";
echo 'attempting sql action<br />';
echo "$sql <br />";
// Run the query once
$result = databaseconnection($sql);
// Now iterate over the results
while ($row = mysql_fetch_assoc($result)){
print_r($row);
}
}
}
function draw_search_form(){
echo '<form action="./numbers.php" method="post">'."\n";
echo 'notes:<br>'."\n";
echo '<input type="text" name="search"><br>'."\n";
echo '<input type="submit" value="Submit">'."\n";
echo '</form>'."\n";
}
posting as an answer, to make it easier to format the corrected function:
function searchtable(){
echo 'searchtable() <br />';
if ($_POST['search'] != "" ){
$search = preg_replace('/[^ \wa-zA-Z0-9_.#()\-+~,?]+/', '', $_POST['search']);
}
if ($search){
$sql = "SELECT * FROM names_numbers WHERE name LIKE \"%{$search}%\"".
" OR phone_address LIKE \"%{$search}%\"".
" OR notes LIKE \"%{$search}%\"";
echo 'attempting sql action<br />';
echo "$sql <br />";
$results = databaseconnection($sql);
while($row = mysql_fetch_assoc($results)) {
print_variable($row);
}
//while ($row = mysql_fetch_assoc(databaseconnection($sql))){
// print_variable($row);
//}
}
}
Man, you are providing an array into while which will always remain true. Please use foreach instead.
$row = mysql_fetch_assoc(databaseconnection($sql))
foreach ($row as $r){
print_r ($r)//extract associative elements
}

Search multiple row separate by comma from mysql using php

It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.

Replacing PHP "undefined variable" error?

so basically I want to make an online dictionary, the word to be searched for is introduced by an input, and I want to make so that if it can't find the word+definition in db to say a message like "We couldn't find any definition" or something like that, in my code because it can't find it , it ways "undefined variable"
<?php
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
include ("footer.php");
?>
P.S.: I know my code is vulnerable to SQLi , but I'll fix that later.
try wrapping the undefined vars in isset
if (isset($word) && isset($description)) {
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else {
echo "Nothing found";
}
Same goes for $search = $_POST['se'];
if(!isset($_POST['se'])) {
echo "Nothing found";
exit;
}
if($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
} else {
echo "$search not found";
}
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(!empty($word) && !empty($description)){
echo '<div class=\"webResult\">';
echo '<h2>$word</h2>';
echo '<p>$description</p>';
echo '</div>";
}else{
echo 'could not find your word';
}
include ("footer.php");
?>
You have to validate your variables if its have value or not
The variables $word and $description are first created inside the while loop. This means that they do not have any scope outside it. This should be the most probable cause, since you are getting a variable not defined error.
There are a couple of options here.
One, you could create these variables outside the while loop, and then assign them new values as you are doing now. Here is what your code might look like, if you choose to do it this way:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
while($row = $dictionary->fetch_assoc())
{
$word = $row['word'];
$description = $row['definition'];
}
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
This will work for you if you have multiple results in the returned mysqli_resource, and want to use the last in the list.
Two, if you are likely to get only one result returned, or if you just want to use the first result in the list, you can have the echo statement inside an if statement that checks if a valid result is returned. For example:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
$row = $dictionary->fetch_assoc();
if($row)
{
$word = $row['word'];
$description = $row['definition'];
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
}
Note:
In the above examples, we use !empty() to check the variables. This is because isset() is pointless here, since we have already created (set) the variables ourselves.
Things to read up:
Scope of variables - http://php.net/manual/en/language.variables.scope.php
empty() function - http://php.net/manual/en/function.empty.php
Object oriented mysqli - http://php.net/manual/en/mysqli.quickstart.dual-interface.php
Try this:
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(isset($word)){
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else{
echo "We couldn't find any definition";
}
include ("footer.php");

how do i display this columns side by side

im having some problem here. basically, i want to compare columns. so i fetched object and the comparing results appeared just as expected. however, it does not return the compare value anymore after i added the fetch_array to view the current table hoping that the compare value would appear beside the compare value. is there any way i could run the compare code and make it appear the table? i tried a query but it would only work in MySQL and not PHP.
$query = "SELECT * FROM system_audit"; $result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'];
echo $row['Type'];
echo $row['Setting'];
echo $row['Value'];
}
while ($row = mysql_fetch_object($result)) {
if($row->Setting != $row->Value) {
echo "X";
} else {
echo "O";
}
}
Your code contains a lot of echo's that have no use. I would suggest learning PHP a bit more.
Your compare is wrong, this should work :
$query = "SELECT * FROM system_audit";
$result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'] . "<br>";
echo $row['Type'] . "<br>";
echo $row['Setting'] . "<br>";
echo $row['Value'] . "<br>";
if($row['Setting'] != $row['Value']) {
echo "X" . "<br>";
}
else {
echo "O" . "<br>";
}
echo "<br>";

Updating multiple SQL records using a single submit button

Scenario: I have multiple text boxes in which a user will enter data into some of them / all of them / or none of them.
Goal: I need to be able to UPDATE multiple records based on what is in the text boxes where the users has entered their data.
Problem: The update statement is not working when I try to update each record for each text box.
Below is the code:
$conn = mysql_connect ($localhost, $user, $pass);
mysql_select_db($db_name, $conn) or die (mysql_error());
$myFile = "/var/www/html/JG/LSP/lsp_ref.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
if (isset($_POST['submit'])) {
foreach ($_POST['notes'] as $key=>$value) {
echo $_POST['notes'][$key];
#echo "<br/>";
//echo "$key";
//echo "<br/>";
$query_update = "UPDATE lsp_active SET Notes = ".$_POST['notes'][$key];
$result_update = mysql_query($query_update);
}
#header ('Location:lsp_display.php');
}
$query = "SELECT * FROM lsp_active";
$result = mysql_query($query);
$field_num = mysql_num_fields($result);
echo "<form method='post' action='lsp_display.php'>";
echo "<table border=1>";
$cols = 0;
while ($row = mysql_fetch_assoc($result)) {
if ( $cols == 0) {
$cols = 1;
echo "<tr>";
foreach ($row as $col => $value) {
print "<th>$col</th>";
}
print "<th>Insert Ticket / Notes</th>";
echo "</tr>";
}
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "<td><input type='text' name='notes[]'/></td>";
echo "</tr>\n";
}
echo "<tr><td colspan=8><input type='submit' name='submit' value='Update'/></td></tr>";
echo "</form>";
mysql_free_result($result);
?>
Now when I print out $_POST['notes'][$key] it spits back out what I give it in the text boxes.
However, the update statement that I have for my SQL isn't updating the database with what I put in.
I am not sure what could be wrong with it :(.
Any help is appreciated!
Thank you!
It looks like you probably need to surround your $_POST in single quotes.
Also use a function to clean the $_POST variable.
For example:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
And then your query:
$query_update = "UPDATE lsp_active SET Notes = '" . escape($_POST['notes'][$key]) . "'";
Edit:
You also might want to put a WHERE statement on the end of your UPDATE query, so that you don't update everything in the table.
"UPDATE lsp_active a SET a.Notes = '" . mysql_real_escape_string($_POST['notes'][$key]) ."' WHERE a.Index = '" . ($key + 1). "'"
Index is a keyword thar refers to indexes, not your column. So I defined an alias, and made it explicit that Im referring to the column. Also, the + 1 on the Where $key since Index is not zero-based like PHP arrays.

Categories