function call inside a function in php not working - php

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!

Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.

You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

Related

How to make json like this from database mysql using php

{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
}
i try this
<?php
include 'koneksi.php';
$idbarang = $_GET['id'];
if($idbarang == !null){
$query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");
$result = array();
$i= 0;
while($row = mysqli_fetch_array($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
} else {
$query = mysqli_query($conn, "SELECT * FROM data_barang");
$result = array();
$i= 0;
while($row = mysqli_fetch_assoc($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
}
?>
and this the result
[
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
},
{
"idbarang": "ID-96037284",
"namabarang": "Sampoerna",
"jenisbarang": "Rokok",
"hargabarang": "12000"
}
]
I think you are asking why you are always going through the ELSE and never the IF. Thats because of this IF test
if($idbarang == !null){
Instead try
<?php
include 'koneksi.php';
if(!empty($_GET['id'])){
$idbarang = $_GET['id'];
You could also simplify that code quite a lot, and protect it from SQL Injection.
// Do the renaming of column names as part of the query
$sql = 'SELECT id_barang as idbarang, nama_barang as namabarang,
jenis_barang as jenisberang, jenis_barang as hargabarang
FROM data_barang';
if(!empty($_GET['id'])){
// add the WHERE clause on to the base query
$sql .= ' WHERE id_barang = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$res = $stmt->get_result();
} else {
$res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);

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?

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

MySql/PHP Query Returning Empty

Here is my code:
$result = mysqli_query($dbconnection, Data::followUser($user_id, $followUser_id));
$result returns empty here.
followUser method in class Data
public static function followUser($user_id, $followUser_id) {
global $database;
$query = "
SELECT *
FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
$num = mysqli_num_rows($result);
if ($num < 1) {
$toast = "Follow";
$query = "
INSERT INTO profile_follow (user_id, follow_id)
VALUES ('{$user_id}', '{$followUser_id}');";
$result = $database -> query($query);
} elseif ($num > 0) {
$toast = "Unfollow";
$query = "
DELETE FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
}
return $toast;
}
I have verified the function works correctly in echoing out $toast. It is either Follow or Unfollow based on condition. I don't think I am handling it right when it comes out?
Supplemental:
Here is what I am doing with $result:
if ($result == "Follow") {
$output["result"] = "Follow";
echo json_encode($output);
} elseif ($result == "Unfollow") {
$output["result"] = "Unfollow";
echo json_encode($output);
}
What does this all accomplish? You've basically got:
mysqli_query($dbconnection, 'Unfollow');
which is NOT a valid query in any way. $result is NOT empty. It's a boolean false, indicating a failed query...

Categories