mysql result into php array - php

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;
}

Related

MYSQL Get a column value and display it in 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'];
}

Creating MySQL Prepared Statement

I have absolutely zero experience protecting my SQL data. I am trying to prevent injection attacks on my web service by using prepared statements. I've followed several tutorials, but each one I've implemented has killed my PHP script. How could I protect this query?
$value = (integer)$_GET["name"];
$sql = "SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = {$value}";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
Here is my attempt:
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$result = $sql->get_result();
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
I'm not really sure why this code doesn't work.
You will have to bind the result and below is the code - it is going to work please try it. please check if there any syntax issues in my code. otherwise it will work.
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT 'coordinates', 'center' , 'content_string' FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$sql->bind_result($coordinates, $center, $content_string)
while($sql->fetch())
{
echo $coordinates;
echo $center;
echo $content_string;
}
Prepared statement with MySQLi
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// set parameters and execute
$username= "John";
$email = "john#example.com";
$stmt->execute();
$username= "Mary";
$email = "mary#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
Php tips and tricks.
http://www.phptherightway.com/
If you are concerned about security this is the topic that I love very much.
What are the best PHP input sanitizing functions?.

PHP mysqli query doesn't return any results

I'm using this code here
<?php
error_reporting(1);
$servername = '127.0.0.1';
$username = '';
$password = '';
$dbname = 'splafpoo_users';
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
printf("<b>Connection failed:</b> %s\n", mysqli_connect_error());
exit;
}
$key = '';
if(isset($_POST['key'])){
$key = $_POST['key'];
}
$query = "SELECT * FROM users WHERE serial='$key'";
echo $query;
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo $row;
?>
Running the query SELECT * FROM users WHERE serial='test' in phpMyAdmin returns the desired result however when trying to display the result using the code above nothing is displayed and I cannot figure out how. How do I display the result?
You're gonna need a good old fashion while loop
while($row = $result->fetch_assoc()) {
echo $row['WHATEVERCOLUMNITISYOUWANT'];
}
also this is most definitely a duplicate.
Use var_dump($row) instead of echo $row or you use echo with a key:e.g. echo $row["user"]

how to replace current_date() to any date type by user

how to replace current_date() to any date type by user
example:
www.example.com/2025-01-04
or any date
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = current_date() ";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
Try this:
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['date'])
and preg_match('/^\d{4}(-\d{2}){2}$/', $_GET['date']) // primitive validation
) {
$date = $_GET['date'];
} else {
$date = date('Y-m-d');
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
$stmt->bind_result($domain);
$data = array();
while ($stmt->fetch()) {
$data[] = array('domain' => $domain);
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
I would recommend using a prepared statement here (assuming you are using mysqli).
A) Because you can dynamically assign either current_date() or variable using user input value to a placeholder.
B) The prepared statement would make this operation more secure since you are escaping all user input.
if (!empty($_POST['date'])) {
$user_date = $_POST['date'];
} else {
$user_date = "current_date()";
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $user_date);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
Depending on how you are getting the date from user, you may need to validate it to make sure that it is in the proper date/time format for mysql.

PHP Database output. Arrays

In first case, i will get full array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row[header];
}
}
mysqli_close($conn);
?>
In the second case, i will get just 1st value from array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$q=$row[header];
}
}
mysqli_close($conn);
?>
<div>
<? echo $q ?>
</div>
What should I do, to make 2nd case work like 1st? I mean, how to put into $q, all values of array, not just the first.
You are not defining $q as an array at all.
$q=array();
...
while ($row = mysqli_fetch_assoc($result)) {
$q[]=$row['header'];
}
...
an example of output :
foreach($q as $header) {
echo $header.'<br>';
}
You are overwriting $q . Try using $q[]=
change $q=$row[header]; line to $q[]=$row[header];
and then not echo $q; but print_r($q);
Try to change this into the while
$q = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
array_push($q, $row['header']); // i guess header is a column of the table
}
}
and then you must have your array when print the $q variable, i mean do an print_r($q)
More info about array_push: http://php.net/manual/es/function.array-push.php
Hope this helps :)

Categories