MYSQL Get a column value and display it in PHP - php

I have a problem
I want to echo the value of "points" column.
What I tried, but did not work:
$stmt = $mysqli->prepare("SELECT points FROM member_profile WHERE user_id = '$firstName'");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['points'];
}
print_r($array);
THis is my current code:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$servername = "db.xxxx.gsp-europe.net";
$username = "xxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxx";
/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
// if don't exist create user with points 0
if ($rows == 0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
?>
What I need in the nutshell: In the end of file, will be a "echo" that will show the current value of "points" column with identificator "user_id". Thats all
Thanks for your time, I appreciate it !

You are getting the result, but aren't fetching the datas.
$stmt->get_result() returns a result set -> mysqli_result and to handle this, you need to call the method fetch_array() from that result.
change your code to :
$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$array[] = $row['points'];
}
If you only want 1 result without using arrays, don't use arrays (yes, yes).
$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$points = $row['points'];
}

Related

displaying a value in array of a table that has duplicate column value php

this may be easy for some of u but I am really having hard time how to do it.
So I have here a code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "db_lms";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = $conn->query("SELECT course_id from enrol group by course_id having count(*)>1");
echo $query->num_rows;
?>
It can echo the number of those that have duplicated value 'course_id'.
Problem: My problem is how can I display those 'course_id' distinctively? I've been searching everywhere but found nothing.
Basing from my table, my desired output should be: "1, 2, 8" because these are course_ids that have a duplicate.
I tried this:
$query = $conn->query("SELECT course_id from enrol group by course_id having count(*)>1");
// $row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$data = [];
while($row = mysqli_fetch_array($query))
{
$data = $row['course_id'];
}
echo json_encode($data);
but it only displaying one value and I don't why.
Hoping someone could help me.
This solved my problem, thank you to those who helped.
$query = $conn->query("SELECT course_id from enrol group by course_id having count(*)>1");
// $row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$data = [];
while($row = mysqli_fetch_array($query))
{
$data[] = $row['course_id'];
}
echo json_encode($data);

mysql result into php array

I'm trying to convert the result that i'm getting from mysql to a php array
can anyone helps me
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "women";
$conn = new mysqli($servername, $username, $password, $dbname);
$id=$_GET['id'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
FROM normalW
where id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($new_array as $array){
echo $row['DAYS'].'<br />';
echo $row['MONTHS'].'<br />';
}
} else {
echo "0 results";
}
$conn->close();
?>
Problem solved Thank you guys
To answer your question you must first declare the new array
$new_array = array();
Then loop through your query results to populated the array
while ($row = $result->fetch()) {
$new_array[] = $row;
}
But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.
$stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");
/* bind parameters i means integer type */
$stmt->bind_param("i", $id);
$stmt->execute();
$new_array = array();
while($row = $stmt->fetch()) {
$new_array[] = $row;
}

PHP for Looping MySql id

I am Using Below Code to First Fetch all 'id' from MySql table.
<?php
$servername = "localhost";
$username = "**";
$password = "**";
$dbname = "**";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$slug = $_GET["category"];
$sql = "SELECT * FROM table WHERE category = '1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dealid = $row["dealid"];
}} else {}
$conn->close();
?>
$dealid should return with all id's but it is returning with only 1.
Now below code is to show data with those id's:-
<?php
$num_rec_per_page=52;
mysql_connect('localhost','**','**');
mysql_select_db('**');
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM table2 WHERE id = $dealid ORDER BY id DESC LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query ($sql);
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<?php include( $_SERVER['DOCUMENT_ROOT'] . '/includes/dealbox.php' ); ?>
<?php
};
?>
But its only showing 1 data because returning id is only 1. I am not able to understand what the issue is. Any help is appreciable and will gift if someone help me out with this issue.
Dear friend all Id's are set into one array and return that array,
eg:
while ($row = mysql_fetch_assoc($rs_result))
{
$dealid[]= $row['id']; //array creation
}
and
return ($dealid);

Ajax post json response issue

I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}

Select a value from a table and use it to update a field of the same table

I am getting some time data in a 12 hour format and i want to convert from 12 hour to 24 hour.This is the script i wrote that uses mysqli.
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "qplat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select the_time from r_data where transaction_type = 'send'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$id = 8980;
while($row = $result->fetch_assoc()) {
$new_id = $id++;
$new_time = $row["the_time"];
echo "the time is: " . $row["the_time"].'<br/>';
$time = date("Hi", strtotime("$new_time"));
$sql2 = "update r_data set 24_hour_time = '$time' where transaction_type = 'send' and id = $new_id";
$conn->query($sql2);
}
} else {
echo "0 results";
}
$conn->close();
?>
The script updates the column 24_hour_time with one time only leaving out all the other rows.
Can this be done using one table or will i have to insert into a different table then move the data back?.
You could solve the problem you are having using codeigniter like this
public function up(){
$query = $this->db->query("select id,the_time from r_data where transaction_type = 'send'");
foreach ($query->result() as $row)
{
$id = $row->id;
$new_time = $row->the_time;
$time = date("Hi", strtotime("$new_time"));
$data = array(
'24_hour_time' => $time
);
$this->db->where('id', $id);
$this->db->update('r_data', $data);
}
}

Categories