SQL pulling first character of each column - php

So I've got a dropdown that has a list of customers that you can select from. It uses a function (that someone else built) which works fine when there are 2 or more customers but dies when there it only one. When there's one customer, each item in the dropdown is the first character of each column for that one customer.
Here is the function:
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if ($check ==1)
{
$row = mysqli_fetch_assoc($run);
return($row);
}
elseif($check >1)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I'm fairly certain that it's the ($check == 1) stuff but I can't work out the best way to re-do all of that to make it work without causing other errors (specifically "cannot modify header")
This is what's called up on the page with the dropdown:
$customers = getCustomerBy('users_user_id',$user['user_id']);
Also, here is the code for the dropdown:
<?
foreach ($customers as $customer)
{
$selected = '';
if (isset($gig['customers_customer_id']) && $customer['customer_id'] == $gig['customers_customer_id'])
{
$selected = ' selected ';
}
echo "\t<option value=\"".$customer['customer_id']."\" $selected>".$customer['customer_company_name']."</option>";
}
?>

The code that builds the dropdown is expecting an array of arrays, but instead when it's a single row you're passing it an array of strings. Treat both cases ($check > 0) the same.
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if($check > 0)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I assume there's copy/paste errors in your query because it doesn't look right.

I don't know how the returning array is used by the rest of your code but you can try the following:
Change:
if ($check ==1) {
$row = mysqli_fetch_assoc($run);
return($row);
}
To this:
if ($check == 1) {
$rows = array();
$rows[] = mysqli_fetch_assoc($run);
return($rows);
}

Related

Multiple Loops running together

$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?

PHP find out student record using functions

Table: student
student.php
<?php
function findStudentRecord()
{
//Db connection
$q1 = "select * from student where gender = 'F'";
$r1 = mysqli_query($dbc, $q1);
$total_records = mysqli_num_rows($r1);
$record = array();
if($total_records > 0)
{
while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
{
$record[] = $row1;
}
}
else
{
//[HERE]
}
return $record;
}
$record = findStudentRecord();
//[HERE]
?>
I want to find female student record but there is no record from my database. How do I return 0 value from function and display "No record found" on my web page in [HERE] section?
if($total_records > 0)
add no else block so it will return an empty array now you can do something like this
$records = findStudentRecord();
if(count($records) === 0) {
echo "No record found";
}
I would not change your function. It returns an array (may be empty) in any case wich is quite consistent.
Instead look at the number of array items returned:
$record = findStudentRecord();
//[HERE]
if(count($record) == 0) {
echo "No record found";
} else {
// what ever
}

only one element of every column is showing when I am fetching In array

When I am fetching data from database in array it's showing only one element of each column. I am using below query:
$stmt = $conn_obj->select(' user ',' * ',' status = "updated" ', $order=NULL, $group=null, $fromRecordNum.','.$recordsPerPage);
and select function is below:
private function tableExists($table) {
//$this->con = $this->createconnection();
$query = 'SHOW TABLES FROM ' . $this->db . ' LIKE "'.trim($table).'"';
//echo ''.$query;
$tablesInDb = mysqli_query($this->con, $query);
if ($tablesInDb) {
if (mysqli_num_rows($tablesInDb) == 1) {
//echo ''.mysqli_num_rows($tablesInDb);
return true;
}
else {
return false;
}
}
}
public function select($table, $row = '*', $where= null,$order=null,$group=null, $limit=null, $join=null){
//$this->con = $this->createconnection();
//echo $join;
$q = 'select'.$row.' from '.$table;
//print_r($q);
if($join != null){
$q .= ' join '.$join;
}
if($where != null){
$q .= ' where '.$where;
print_r($q);
}
if($group != null){
$q .= 'group by'.$group;
//print_r($q);
}
if($order != null){
$q .= 'order by'.$order;
}
if($limit != null){
$q .= 'limit '.$limit;
print_r($q);
}
if ($this->tableExists($table)) {
$query = mysqli_query($this->con, $q) or die(mysql_error());
//print_r($query);
if ($query) {
$this->numResults = mysqli_num_rows($query);
//echo $this->numResults;
for ($i = 0; $i < $this->numResults; $i++) {
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if (!is_int($key[$x])) {
if (mysqli_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if (mysqli_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
//print_r($this->result);
return $this->result;
} else {
return false;
}
} else{
return false;
}
}
I am fetching it with foreach loop as follow:
foreach($stmt as $row)
{
echo $row['user_Id'];
}
output is= 7 t : 2 2 2 u W u 2
and if I print whole array with print_r($row) then
output is= test ::1 2015-07-30 11:42:09am 2015-07-29 12:42:09pm 2015-07-30 12:28:57pm updated call_activated uninstall 2015-07-30 12:31:07pm.
If database has only one row with specified query then above problem is creating.
But in the case of two row with the specified query, its working fine as I want.
For multiple results, you are getting an array of arrays of elements.
For a single result, you are getting an array of elements.
So, for a single element, you have one foreach loop too many.
if in your example:
foreach($stmt as $row) {
echo $row['user_Id'];
}
Assuming $stmt contains the return value of your query:
foreach($stmt as $row) {
if (isset($row['user_Id'])) {
// do something with one single result record
} else {
foreach ($row AS $innerRow) {
// do something with each result record
}
}
}

I want to return two results from one function in php

Here is my function in DB_Functions.php, i want to get two different values from two different tables in single function only here is the code what i have tried so far but the values are coming null.
public function getUserMetvalue($exname,$fname) {
$result = mysql_query("SELECT metvalue FROM fitnessactivitylist WHERE activityname='$exname'") or die(mysql_error());
$result1 = mysql_query("SELECT weight FROM users WHERE name='$fname'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
$no_of_rowss = mysql_num_rows($result1);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
if ($no_of_rowss > 0) {
$result1 = mysql_fetch_array($result1);
return $result1;
}
return $result;
} else {
//exercise name not found
return false;
}
}
here is my index.php
//TAG METVALUE
if ($tag == 'metvalue') {
$exname = $_POST['exname'];
$fname = $_POST['fname'];
$usermetvalue = $db->getUserMetvalue($exname,$fname);
if ($usermetvalue != false) {
$response["success"] = 1;
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
echo json_encode($response);
}
else {
$response["error"] = 1;
$response["error_msg"] = "No exercise found!";
echo json_encode($response);
}
}
Spot the differences:
$result = mysql_query("SELECT metvalue etc...
^^^^^^^^
$result1 = mysql_query("SELECT weight etc...
^^^^^^
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
^^^^^^
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
^^^^^
You fetch fields which aren't used later, then attempt to access fields which weren't fetched in the first place...
function a_function() {
$a = 'Learn';
$b = 'Programming.';
return array($a, $b);
}
list($one, $two) = a_function();
echo $one . ' ' . $two;

Store query results in a different table in PHP/MySql

I'm using PHP/MySql and I'm trying to team users into pairs based on a skill that they have. I have an existing table for users, and an existing table for the teams.
For example, I executed a query which returned 6 members which needs to be paired up into a team.
SELECT * FROM users WHERE skill = 'Office'
users
id/name/skill
1/Bob/Office
2/Ted/Office
3/Tim/Office
4/Bill/Office
5/Shawn/Office
6/Gab/Office
These results must be then paired up, and the expected output should be:
teams
name/member
Office1/Bob
Office1/Ted
Office2/Tim
Office2/Bill
Office3/Shawn
Office3/Gab
Once 2 members are placed in a team, the team name should increment by one.
Any help will be greatly appreciated Thanks.
Edit: I tried this:
$results = mysql_query("SELECT * FROM users WHERE skill = 'Office'");
$numrows = mysql_num_rows($results); $name ="";
if($numrows!=0) {
while($row = mysql_fetch_assoc($results)) {
$name = $row['userName'];
}
}
//For incrementing the team name
$namectr=0;
for($ctr=0;$ctr<$results_num;$ctr++) {
if($ctr%2==0) {
$query = mysql_query("INSERT INTO teams VALUES ('Office$namectr','$name')");
$ctr++; if($ctr%2==1) {
$query = mysql_query("INSERT INTO teams VALUES (Office$namectr','$name')");
$namectr++;
}
}
}
why not try:
$result = mysql_query("SELECT * FROM users WHERE users.skill = 'office'");
$count = 0;
$sqlcount = 0;
$offcount = 1;
while ($source = mysql_fetch_array($result)) {
if ($count < 1) {
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else if ($count >= 1) {
$offcount++;
$count = 0;
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else {
echo "ERROR" . mysql_error();
}
}//end while
$sqlcount = 0;
while ($result[$sqlcount] != "") {
if ($source = $result) {
} else {
echo "ERROR! " . mysql_error();
}
}//end while
Couldn't you do your database query, then do something like the below:
$count=0;
$team=1;
$teams = array();
foreach($result as $output){
if($count % 2 == 0){
// if even number, reset count and increment position
$count=0;
$team++;
}
$teams[] = $output['skill']." ".$team." - ".$output['member'];
$count++;
}
Something like the above, but it is untested, but should work in theory.

Categories