Implement If condition in PHP array - php

I am new to PHP function. I think following problem can be solved using function. Here I am able to store html form data in database which is passed from ajax using following code. But I am little bit confused where to implement if condition. If Data has been submitted, I want to stop data replication.
My working php code
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
Now, I want to include above code in following else condition.
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
When I try to merge code, I can't handle. Please help me

You have pretty much everything, you just need to wrap it in a function like this:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
And then you call it like this:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}

Related

PHP populate array inside a function

i have a small problem with my php code.
i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.
<?php
$returnData = array();
class Clients
{
public function readAll(){
$query = "SELECT * FROM clients";
$result = $this->con->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$returnData['clientsList'][] = $row;
}
return $returnData;
}
else{
echo "No found records";
}
}
}
if ($auth->isAuth()){
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientsObj->readAll();
}
echo json_encode($returnData);
?>
and the result is like that, but without clietslist
{
"message": "you are loggedin, so is ok"
}
Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.
You need to get return value of function in a variable:
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] = $clientsObj->readAll();
$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.
I suggest you to read about variable scope in php.
https://www.php.net/manual/en/language.variables.scope.php
Now, You will need to store returned value from function in a variable
like this
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray = $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];

How to fetch and dispaly specific data with PDO

I'm having issues making my project for lesson attendance and management work the way I'd like it to. Sorry if this has already been addressed here. After days of searching, I still cannot for the life of me find a way to display a limited result set from my DB query to my home page.
This part of the project gets all Towns listed on my homepage like so:
Verona
Mantova
Rovereto
Bardolino
...
What I'd rather want is to get control over whatever is displayed! Specifically, I'd like to have ONLY Rovereto and Bardolino returned (as example). I'm thinking of probably doing this with additional page e.g. index1.php so when this page is loaded it will show only desired values and not all fetched values!
The search function result is also case sensitive. If I type "Bardolino", I get result but with "bardolino", no joy at all. I'm new to this, please help me out. Thank you very much.
File index.php:
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Lesson Number</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<?php
for($i=0; $i < count(User::get_all_users()); $i++){
echo "<tr>";
echo "<td>".User::get_all_users()[$i]['id']."</td>";
echo "<td>".Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['number']."</td>";
echo "<td>".show_town(Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
?>
File user_controller.php:
if(isset($_GET['type']) && $_GET['type'] == 'search'){
global $user_search_list;
$user_search_list= array();
for($i=0; $i < count(User::get_all_users()); $i++){
$user = User::get_all_users()[$i];
$lesson_number = Lesson::get_lesson_by_id($user['lesson_id'])['number'];
$town_name = show_town(Lesson::get_lesson_by_id($user['lesson_id'])['town_id']);
if(strpos($lesson_number,$_GET['search_term']) !== False ||
strpos($town_name,$_GET['search_term']) !== False)
{
$user_search_list[] = $user;
}
}
$_SESSION['search_list'] = $user_search_list;
header("Location: search_user_list.php");
exit();
}
if(isset($_GET['type']) && $_GET['type'] == 'reserve'){
$user = User::get_user_by_id($_GET['user_id']);
if(!empty($_GET['seat_id'])) {
if(count($_GET['seat_id']) * $user['price'] > intval(Balance::get_user_balance($_SESSION['user_id'])['amount'])){
header("Location: reserve.php?user_id=".$user['id']."&balance_error=set");
exit();
}else{
foreach($_GET['seat_id'] as $seat_id){
echo $seat_id;
echo "<br>";
Reservation::create_reservation('', $_SESSION['user_id'], $_GET['user_id'], $seat_id, getdate()[0]);
Balance::update_balance($_SESSION['user_id'], intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) - intval(User::get_user_by_id($_GET['user_id'])['price']));
Seat::reserve_seat($seat_id,$_SESSION['user_id']);
Action::create_action('', "User - ".$_SESSION['user_id'].'reserve Seat ID - '.$seat_id. " on User ID - ".$_GET['user_id'],"reserve" , getdate()[0]);
}
if(count(Reservation::get_all_reservations_by_user($_SESSION['user_id'])) == 5){
Balance::update_balance($_SESSION['user_id'] ,intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) + 10);
header('Location: index.php?reserve_success=set&reward=set');
exit();
}
header('Location: index.php?reserve_success=set');
exit();
}
}
else{
header("Location: reserve.php?user_id=".$user['id']."&seat_error=set");
exit();
}
}
function show_town($id){
return Place::get_place_by_id(Town::get_town_by_id($id)['place_id'])['name'].
}
File User.php:
class User
{
static $id;
static $lesson_id;
static $starting_date;
static $starting_time;
static $arrival_time;
static $price;
static function create_user($id, $lesson_id, $starting_date, $starting_time, $arrival_time, $price){
global $db;
$sql = "INSERT INTO `lesson_database`.`users` (`id`, `lesson_id`, `starting_date`, `starting_time`, `arrival_time`, `price`) VALUES (NULL, '".$lesson_id."', '".$starting_date."', '".$starting_time."', '".$arrival_time."', '".$price."');";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
static function get_all_users(){
global $db;
$sql = "SELECT * FROM `users`";
$db_result = $db->query($sql);
if($db_result){
return $db_result->fetchAll();
}
else {
return False;
}
}
static function get_user_by_id($id){
global $db;
$sql = "SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1";
if(!isset($sql)){
echo "not set";
}
$db_result = $db->query($sql);
if($db_result){
$db_row = $db_result->fetch(PDO::FETCH_ASSOC);
if($db_row){
return $db_row;
}
else {
return False;
}
}
return False;
}
static function delete_user($id){
global $db;
$sql = "DELETE FROM `lesson_database`.`users` WHERE `users`.`id` = '".$id."'";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
}
I feel a little bit like you've jumped ahead and skipped some basics as lots of this doesn't make sense.
Firstly, you've said about using PDO in the title but you're not using PDO in your queries, you really need to be using PDO so if you're not sure how then try and find a good tutorial about using prepared statements.
Secondly, you're doing loads of extra calls within loops and duplicating calls all over the place so I think you could do with looking for a tutorial on design patters and think about how you could streamline this code.
As a very basic you could get all your users once by using a fetchAll (or fetch_assoc i think in mysqli) and then just loop through that variable e.g.
<?php
$users = User::get_all_users;
foreach($users as $user){
$lesson = Lesson::get_lesson_by_id($user['lesson_id']);
echo "<tr>";
echo "<td>".$user['id']."</td>";
echo "<td>".$lesson['number']."</td>";
echo "<td>".show_town(lesson['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
as for your search the simplest way would be to pass a search string in the url and use global $_GET['searchString'] (obviously you will need to sanitize the string) and then search for results directly in sql such as
SELECT * FROM table WHERE town LIKE . $yourvariable .% (ideally in your newly learned PDO style)
then it will be both not case sensitive and will also mean you've got the data in the first place so you don't waste time looping through a bunch of extra rows.
If you need to make this case insensitive in the meantime then the simplest way is to convert the search and the comparison string to the same case (strtolower for example) and then they will match
It also strikes me that your database might not be in good shape as I would be surprised to find that a user table contains lesson ids, so you might want to look into the idea of database normalisation, this will then allow you to do some more creative queries and more easily gather together accurate information for whatever your task is (i.e. make it scalable and manageable).
I hope some of that is helpful, sorry it's not a quick answer but it's not a quick problem I think. Don't fear though, we all started somewhere!!

How to display SQL result separately

I'm currently making a webpage which is meant to show all it's content from the database. So I made an SQL command which selects the data needed for only 1 particular field on the webpage.
Is it possible to make the SQL command so that it get's all the content for the page at once and that ill still be able to display it separately?
If so, how? Thanks
function dbGet() {
global $conn;
global $return;
$sql = SELECT * FROM testTable;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$return = $row["text"];
return $return;
}
}
else {
echo "0 results";
}
// $conn->close();
}
You can use in this way through which you can identify records has been there or not.
function dbGet() {
global $conn;
// I am not sure what is the datatype of $return here.
// if it's having a predefined format,
// please push the records into $return instead of creating as an array,
// which will be taken care by framework if any you are using.
// global $return;
$return = array('status' => false, records => []);
$sql = "SELECT text FROM testTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$return['status'] = true;
while($row = $result->fetch_assoc()) {
$return['records'][] = $row["text"];
}
}
// $conn->close();
return json_encode($return);
}
Just echo the results inside while loop instead of returning in whatever format you wish
If you are using php, you can try something like
echo $row["text"];
Hope it helps
Let me know if you require any further help
First you should fix your return code as #AbraCadaver mentioned :
$return[] = $row["text"];
Then you can use foreach in your html :
<?php
foreach($return as $r){
echo $r['text'];
}
?>
I think a Json encoding : json_encode will work well.
Try this: http://php.net/manual/pt_BR/function.json-encode.php

Pass mysql_query results to foreach

I used the following code to to get list of users facebook friends and ccheck it against users in an app database. This code would return the users of the app, who are Facebook friends of the user.
$friends_set = '(';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error());
while($row = mysql_fetch_array($res)) {
echo $row['fb_id']. "". $row['first_name'];
echo "<br>";
}
$data['top_friends']=$res;
$this->load->view('myview');
This code works. It is in a controller of my codeigniter application and it successfully echos the correct data onto the page.
However now I need to print the result of the query in a for each statement in my view like this:
<?php foreach ($top_friends as $me) : ?>
<div >
<p><?php echo $me['first_name']; ?></p>
<?php endforeach; ?>
However when I try getting the query results in the view using the for each it doesn't work.
How do i fix this?
You could try it the codeignitor way, Create a model function say get_top_friends and i assume that you are passing a comma separated string as argument like $fb_id = '45,65,78,89'. Say facebook_model is the name of the model then :
class Facebook_model extends CI_Model{
//other functions and constrcutor here
//function to get the top friends
function get_top_friends($fb_id){
$fbId = explode(",",$fb_id)
$this->db->select('*');
$this->db->where_in('fb_id',$fbId);
$this->db->order_by('points','desc');
$this->db->limit(10);
$query = $this->db->get('user');
if ($query->num_rows() < 1) return FALSE;
return $query->result_array();
}
}
And make change in your code as below:
$friends_set = '';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = $this->facebook_model->get_top_friends($new_set);
$data['top_friends']=$res;
$this->load->view('myview',$data);
And now in view you can try
foreach ($top_friends as $me){
echo $me['first_name'];
}
[Updated for user ]
If you want to do it as in your question : then try,
$result = array();
while($row = mysql_fetch_array($res)) {
$result[] = $row;
}
$data['top_friends']=$result;
$this->load->view('myview',$data);//pass data to view

Inserting multivalues from textbox into the MySQL Database using PHP

I'm having a problem with my PHP and MySQL project . I wanted to insert multi collumn value into the database but the truth is, im already confused by the codes. it's like this if you would like to take a look:
if(!empty($_POST['brando'])){
$A="brand = '$brando'";}
else{
$A=" ";}
if(!empty($_POST['prnameo'])){
$B="product_name = '$prnameo'";}
else{
$B=" ";}
if(!empty($_POST['prido'])){
$C="product_id = '$prido'";}
else{
$C=" ";}
if(!empty($_POST['prcolo'])){
$D="color = '$prcolo'";}
else{
$D=" ";}
if(!empty($_POST['priceo'])){
$E="price = '$priceo'";}
else{
$E=" ";}
$sqlq="UPDATE $tbl_name2 SET $A $B $C $D $E where id='$id'";
mysql_query($sqlq);
I noticed that querying multivalue command into a database requires comma such as:
mysql_query("UPDATE $tablename SET collumn1='value', collum2='value' where id='value'");
and now i cant put any comma or "," in any of those codes, making the PHP page unable to send other variable values into the server.
even if i change the coding to this:
$sqlq="UPDATE $tbl_name2 SET $A , $B , $C , $D , $E where id='$id'";
it'll produce what else but damn errors.
so i would like to ask for help if you know what i'm talking about. i know, it sounds like i've been stressed out by the codings.
ooh, this code too, i forgot to put it for these.
for ($help_given=1, $help_given++)
{
echo "Thanks";
}
Try to implode() an array with "," ,like this:
<?php
if(!empty($_POST['brando'])){
$value[] ="brand = '$brando'";
}
if(!empty($_POST['prnameo'])){
$value[] ="product_name = '$prnameo'";
}
if(!empty($_POST['prido'])){
$value[] ="product_id = '$prido'";
}
if(!empty($_POST['prcolo'])){
$value[] ="color = '$prcolo'";
}
if(!empty($_POST['priceo'])){
$value[] ="price = '$priceo'";
}
$sqlq="UPDATE $tbl_name2 SET " . implode(",",$value)." where id='$id'";
mysql_query($sqlq);
?>
Then, you'd better to use "mysql_escape_string" or "PDO::prepare" method to prevent SQL injection.
if(isset($_POST['brando']))
{
$brando=mysql_escape_string($_POST['brando']);
$A="brand = ".$brando;
}
else
{
$A=" ";
}
if(isset($_POST['prnameo']))
{
$prnameo=mysql_escape_string($_POST['prnameo']);
$B="product_name = ".$prnameo;
}
else
{
$B=" ";
}
if(isset($_POST['prido']))
{
$prido=mysql_escape_string($_POST['prido']);
$C="product_id = ".$prido;
}
else
{
$C=" ";
}
if(isset($_POST['prcolo']))
{
$prcolo=mysql_escape_string($_POST['prcolo']);
$D="color= ".$prcolo;
}
else
{
$D=" ";
}
if(isset($_POST['priceo']))
{
$priceo=mysql_escape_string($_POST['priceo']);
$E="price = ".$brando;
}
else
{
$E=" ";
}
$tbl_name="mytable";//to set
$id='primary_key';//to set
$sqlq="UPDATE $tbl_name SET $A, $B, $C, $D, $E where id='$id'";
mysql_query($sqlq);
Just put values where I have commented as //to set...

Categories