How do I find the first column with no data?
//column pet1='dog'
//column pet2=''
//column pet3=''
//column pet4='cat'
if($F=="getempty"){
$uid=$_GET["uid"];
$sql = mysql_query("SELECT DISTINCT pet1,pet2,pet3,pet4 FROM a WHERE uid='".$uid."' AND pet1='' OR pet2='' OR pet3=''OR pet4=''");
while($column=mysql_fetch_field($sql)){
$empty=$column->name;
echo json_encode(array("empty"=>$empty));
}
}else{}
I keep trying but so far it just returns all column names if one is empty
pet1,pet2,pet3,pet4
DISTINCT will combine the rows which are exactly alike (having all the selected columns the same) and return them.
To get the name of the first empty column, use a query like:
SELECT
CASE
WHEN pet1 = '' THEN 'pet1'
WHEN pet2 = '' THEN 'pet2'
WHEN pet3 = '' THEN 'pet3'
WHEN pet4 = '' THEN 'pet4'
ELSE NULL
END AS firstempty
FROM a
WHERE uid = '$uid';
The idea is that the CASE statement checks each one in order, and finding an empty one returns the column name without checking the rest of them.
Don't forget to escape $uid with mysql_real_escape_string() before passing it to the query.
$uid = mysql_real_escape_string($uid);
Since we're now getting the column name inside a field called firstempty, we'll also need to change the way it's fetched:
while($row = mysql_fetch_assoc($sql)){
$empty = $row['firstempty'];
echo json_encode(array("empty"=>$empty));
}
Related
This code only reads the first value present in the column. If the value posted in the html form matches the first value, it inserts into the database. But I want to check all the values in the column and then take the respective actions.
For example, if i give input for 'ppincode' and 'dpincode' as 400001, it accepts. but if i gave 400002, 400003,..... it displays the alert even if those value are present in the database
DATABASE:
pincode <== column_name
400001 <== value
400002
400003
400004
...
also i tried this
$query = "SELECT * FROM pincodes";
$result = mysqli_query($db, $query);
$pincodearray = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$pincodearray[] = $row;
}
}
If I understand well - you want to compare value from POST request with all retrieved records saved in DB and if it matches - perform action.
If so, I would recommend using for(each) loop. Example:
if( !empty($row){
foreach( $row as $key ){
if($key['pincode'] == $ppincode && $key['pincode'] == $dpincode){
// your action goes here
}
}
}
Additional tip: use prepared statements :)
SELECT count(*) FROM table WHERE ppincode=ppincode AND bpincode=bpincode
if this return 0 then insert or else show alert.
I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).
I want to return all the rows from a specific table when a specific column value is contained in a PHP variable, e.g : row 34: has column 'xyz' value equal to = "rabbit" and my php variable is $var = "rabbit,robert,teen", and because the "xyz" column value is contained in $var I want it to be selected.
How can I do that?
convert the comma separated list to sql format and place in the query
$query = "select blah blah WHERE xyz IN ('".str_replace("," ,"','", $var)."');"
If I understand your question correctly, you're looking for something like this:
$arr = explode(',', $var);
$where_in_val = '';
foreach($arr as $value){
$where_in_val.= "'$value',";
}
$where_in_val = substr($where_in_val,0,-1);
Then your query might be something like this
SELECT * FROM my_table WHERE xyz IN ($where_in_val)
Note: Don't forget cleaning/escaping/sanitizing the user's input.
Noticed a rather large problem. When I join two tables togeter the fact that there is a column called ID in both of them causes the wrong tables ID to be used in a PHP equasion later on.
The simple solution would be to change the column name, but there are other standards thoughout the database too including columns called name in every table and title in many of them.
Is there a way around this or should I rename the entire database to ensure that there are no duplicate columns.
THE CODE FOR REFERENCE
$criteria = "SELECT *
FROM voting_intention,electors
WHERE voting_intention.elector = electors.ID
AND electors.postal_vote = 1
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
AND electors.telephone > 0"
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria"); while($row = mysql_fetch_array($the_elector)) {
return $row['ID']; }
While "Gunnx" solution is perfectly acceptable, I'd like to present an alternative since you appear to be using only the ID column of the result.
SELECT
electors.ID
FROM
voting_intention,electors
....
I wrote this function to assist in doing this. Basically it prepends the table name to the fields name of an associated array.
while($row = mysql_fetch_array($the_elector))
{
return $row['ID'];
}
would become
while($row = mysql_fetch_table_assoc($the_elector))
{
return $row['voting_intention.ID'];
}
function:
function mysql_fetch_table_assoc($resource)
{
// function to get all data from a query, without over-writing the same field
// by using the table name and the field name as the index
// get data first
$data=mysql_fetch_row($resource);
if(!$data) return $data; // end of data
// get field info
$fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
// if no field info then just use index number by default
$fields[$index]=$index;
}
else
{
$fields[$index]='';
// deal with field aliases - ie no table name ( SELECT T_1.a AS temp, 3 AS bob )
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
// deal with raw data - ie no field name ( SELECT 1, MAX(index) )
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>
mysql_fetch_row will get the data as a numerical array
Trying to do a search and replace using php/mysql. I do this in specified table headers/columns. it works fine when my search term has a value. However i want to search for an empty field in a specified column and replace with a value. it fails to do a search and replace when my search term is an empty string. Any help?
$SearchAndReplace_header = isset($_POST['SearchAndReplace_header']) ? $_POST['SearchAndReplace_header'] : "";
$SearchAndReplace_search_term = isset($_POST['SearchAndReplace_search_term']) ? $_POST['SearchAndReplace_search_term'] : "";
$SearchAndReplace_replace_with = isset($_POST['SearchAndReplace_replace_with']) ? $_POST['SearchAndReplace_replace_with'] : "";
//foreach($fields as $key => $val) {
// if($SearchAndReplace_header == "all" || ($SearchAndReplace_header == $val)) {
// replace column value with parameter value
$sql = "UPDATE ".$table_name." SET ".$val." = REPLACE(".$val.",'".$SearchAndReplace_search_term."','".$SearchAndReplace_replace_with."')";
$db->query($sql);
// }
// }
You can't do a replace on an empty field, you'll have to set the field directly.
UPDATE table
SET column = 'value'
WHERE column = '' or column is null
If you want to cover both cases in a single query, you could do something like this:
UPDATE table
SET column = CASE
WHEN column IS NULL OR COLUMN = ''
THEN 'replace'
ELSE
REPLACE(column, 'find', 'replace')
END CASE