I want to create this array with data from my database..
| Day | Comment | OtherComment |
|-----|---------|--------------|
| 1 | hallo | hallohallo |
|-----|---------|--------------|
| 2 | hey | heyhey |
|-----|---------|--------------|
| 3 | hello | hellohello |
|_____|_________|______________|
I tried a lot of things, but could get the result I wanted, this is my latest code:
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return $rResult;
$dim = array();
while ( $row = mysql_fetch_assoc($result) )
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
Using MySQLi
Okay since we plan to do this using MySQLi, I'd like to introduce you to the object oriented way of using mysqli, so you don't have to keep passing the database link around in your calls. We'll need to make a change to how we connect:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
// So the user an error instead of exiting like this
// in your production code!
echo "Connect Error ({$mysqli->connect_errno}) {$mysqli->connect_error}";
exit;
}
As noted in the comment inline, instead of exiting and showing the user a very ugly looking single line error, you should instead show them a more friendly error page. Next we're going to use something called a prepared statement to make sure our data is sanitized:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
$stmt = $mysqli->prepare($sql);
if(!$stmt) {
// Let the user know the query failed!
}
This is a bit unfamiliar looking for those of us used to your standard queries with variables inlined:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
Basically the question marks act as placeholders that we will fill with the actual values we want. Please note that for string values, you don't need to put quotes around the value:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = '?'"; <-- This is wrong!!
Next is the core of prepared statements:
$stmt->bind_param('is', $p_iUserid, $this->Day);
Here, we are telling MySQLi what we want to replace the question mark placeholders with. The first argument to bind_param indicates the type of data we're replacing. This allows MySQLi to perform sanity checks.
In this case i represents an integer value, and s represents a string value. Then we list our values in the order they appear in the query. $p_iUserid replaces the first ? and $this->Day replaces the second ?. Now we execute this statement so we can get the actual data:
$stmt->execute();
The next part is a very interesting feature:
$stmt->bind_result($diaryOpmerkingen, $diaryDoctorcomment);
This looks complicated at first, but its actually makes things very easier when working with the query. What this function does is create the variables $diaryOpmerkingen and $diaryDoctorcommen fills them with the actual column data when we loop through our results:
$dim = array();
while ($stmt->fetch()) {
$dim[$diaryOpmerkingen][$diaryDoctorcomment] = array($diaryOpmerkingen, $diaryDoctorcomment);
}
Notice how we don't have to use associative arrays and can instead utilize cleaner variable names? Finally, since with prepared statements, you can keep swapping in different values, we need to free our prepared statement once we're done with it:
$stmt->close();
Finally, we close our main database connection:
$mysqli->close();
Here is the full code listing for reference:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
// So the user an error instead of exiting like this
// in your production code!
echo "Connect Error ({$mysqli->connect_errno}) {$mysqli->connect_error}";
exit;
}
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
$stmt = $mysqli->prepare($sql);
if(!$stmt) {
// Let the user know the query failed!
}
$stmt->bind_param('is', $p_iUserid, $this->Day);
$stmt->execute();
$stmt->bind_result($diaryOpmerkingen, $diaryDoctorcomment);
$dim = array();
while ($stmt->fetch()) {
$dim[$diaryOpmerkingen][$diaryDoctorcomment] = array($diaryOpmerkingen, $diaryDoctorcomment);
}
$stmt->close();
$mysqli->close();
Using Standard MySQL
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
Only selecting columns you need. Very good. However since we're already using double quotes, we don't need the concatenation operator. Also it's a good idea to break out SQL keywords from column and values consistently:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = $p_iUserid
AND DiaryDay = '{$this->Day}'";
Onward:
$rResult = mysqli_query($link, $sql);
You're mixing up the $link and $sql parameters, and also mixing mysqli and mysql series of functions up. Also unless you have another connection somewhere else, you can just use $sql as the sole parameter:
$rResult = mysql_query($sql);
Now you're returning the result:
return $rResult;
but by doing the the next pieces of code don't get called, so we can get rid of that. Finally we loop through the results:
$dim = array();
while ( $row = mysql_fetch_assoc($rResult) )
{
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
}
Here's the final code:
// Make sure $this->Day is sanitized if it's user input data
$day = mysql_real_escape_string($this->Day);
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = $p_iUserid
AND DiaryDay = '$day'";
$rResult = mysql_query($sql);
if(!$rResult) {
//Do something with the error
}
$dim = array();
while ( $row = mysql_fetch_assoc($rResult) )
{
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
}
Check out this page, for some sql functions 5 useful PHP functions for MySQL data fetching
Try:
while ( $r = mysql_fetch_assoc($result) )
$dim[$r['day']] = ["DiaryOpmerkingen" => $r['DiaryOpmerkingen']], 'DiaryDoctorcomment' => [$r['DiaryDoctorcomment']];
$i=0;
while ( $row = mysql_fetch_assoc($result) )
{
extract($row);
$arr[$i]=$DiaryOpmerkingen;
$i++;
$arr[$i]=$DiaryDoctorcomment;
$i++;
}
Please try this code
Related
I have sql query that saved on table.
tbl_query
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
Then on PHP code:
$query = mysqli_query($con, "SELECT * FROM tbl_query");
while($data = mysqli_fetch_array($query))
{
//SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
$getQuery = $data['sql_query'];
$qTotal = mysqli_query($con, $getQuery);
$dTotal = mysqli_fetch_array($qTotal);
echo $dTotal['TOTAL'];
}
When I tried to run that code, it show me result of total is 0. But if I remove this WHERE badgeid_fk = '$getBadgeID' on query data, the result is OK not 0.
How to keep execute the query even if there is an variable '$getBadgeID'
PHP treating this variable as a string, thats why result generating this query
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID' // its not converting your variable with 150502
Here you can use alternate name or you can use with delimiter like:
Your current query is:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
Change your query with:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ':getBadgeID'
Now, you need to use str_replace to replace delimiter with your variable like:
while($data = mysqli_fetch_array($query))
{
$getQuery = str_replace(":getBadgeID", $getBadgeID , $data['sql_query']);
}
Why i am using delimiter here, because your variable $getBadgeID having defined value inside your php script and its not dynamic.
In our chat conversation, #executable suggest an another solution to use prepared statement.
Edit:
As per discussion with #Bananaapple, i am adding this comment for future visitors, Prepared Statement is an another solution which is more secure, if you want to avoid SQL injection, then choose prepared statement.
The recommend way is to use the prepared statements to sanitize the query and protect you from SQL injection. The following comic give an example of what is SQL injection.
For answering the question we discover that in your query the variable $getBadgeID was read as text and not as variable. I recommend you to use this code which use the prepared statements :
<?php
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}
$conn->close();
var_dump($total);
If you want more debugging :
<?php
if(isset($getBadgeID) and $getBadgeID != ""){
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}else{
echo "Query is wrong";
}
$conn->close();
var_dump($total);
}else{
echo 'Variable $getBadgeID is empty';
}
All I need is to produce a row. I've looked at all the samples and I cannot for the life of me get the right information. Hence help is required please.
Connection to DB in the usual way. Here is my code for the query.
$sql = "SELECT * FROM table WHERE `u_password` = $pword AND `user` = $uname LIMIT 1";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
I've got a count in there and it produces a result of 1.
The error I get is
'Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result'
Help would be appreciated.
The error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Almost always means that the query failed for some reason, thus $result = mysqli_query returns FALSE rather than a mysql_result object so anything that then tries to use $result as an object will not work for obvious reasons.
The issue with your query is that text column data must be wrapped in quotes like this
$sql = "SELECT *
FROM table
WHERE `u_password` = '$pword' AND `user` = '$uname' LIMIT 1";
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
You should use parameterized queries to avoid this.
$sql = "SELECT *
FROM table
WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
// its also a good idea to check the staus of a prepare
// and show the error if it failed, at least while testing
if ( $stmt === FALSE ) {
echo mysqli_error($mdb);
exit;
}
$stmt->bind_param('ss', $pword, $uname );
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['seeking'];
You need to use prepared statements (in actuality you could get it to work by quoting your strings but prepared statements are much better). Like so:
$sql = "SELECT * FROM table WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
$stmt->bind_param("ss",$pword,$uname);
if ($stmt->execute()) {
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
} else { /* something went wrong */ }
I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I'd like to know how to select a single value from my MySQL table. The table includes columns username and id amongst others (id is auto-increment and username is unique). Given the username, I want to set a session variable $_SESSION['myid'] equal to the value in the id column that corresponds to the given username. Here's the code that I've already tried:
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;
So far I'm getting:
Catchable fatal error: Object of class stdClass could not be converted to string.
Casting $value to type string does not fix the problem.
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
You do this by using mysqli_fetch_field method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5
mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
PDO
The simpler option is PDO which has a neat helper function fetchColumn():
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
Proper PDO tutorial
MySQLi
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
Since PHP 8.1 you can also use fetch_column()
$stmt->execute();
$value = $stmt->get_result()->fetch_column();
Try this
$value = mysql_result($result, 0);
When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here
It is quite evident that there is only a single id corresponding to a single username because username is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
O/P
+----+
| id |
+----+
| id |
+----+
i.e. 'id' actually is treated as a string not as the id attribute.
Correct synatx:
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
Complete code
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}
Apologies in advance because I'm really unsure how to ask this question so if you need to know anything then please comment rather than downvote and I will edit.
I have teaser links on my main page which when clicked open up a window with the full article. I'm currently converting my MySQL code over to PDO and have gotten a little stuck.
In MySQL I used to be doing the following (Here, $foo_query is the query from the first page):
$id = $_GET['id'];
$sql = "SELECT id, postdate, title, body FROM FooBarTable WHERE id = $id";
if ($foo_query = mysql_query($sql)) {
$r = mysql_fetch_assoc($foo_query);
$title = $r["title"];
$body = $r["body"];
}
Which is simple to understand to me. I've been trying to convert this using what I know, and it turns out I don't know very much. So far I have the following:
$id = $_GET['id'];
$sql = $DBH->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
if ($foo_query = $DBH->query($sql)) {
$r->setFetchMode(PDO::FETCH_ASSOC);
$r = $foo_query->fetch();
$title = $r["title"];
$body = $r["body"];
}
$sql->execute();
This brings up an error of 'PDO::query() expects parameter 1 to be string'. This is for the 'if' line.
Have I even written any of that PDO correctly? What would I need to do from here? A friend has recently taught me MySQL, but he doesn't know PDO at all which means I can't ask his advice (not all that helpful...)
This is the correct way, with comments:
try {
//Connect to the database, store the connection as a PDO object into $db.
$db = new PDO("mysql:host=localhost;dbname=database", "user", "password");
//PDO will throw PDOExceptions on errors, this means you don't need to explicitely check for errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//PDO will not emulate prepared statements. This solves some edge cases, and relives work from the PDO object.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Prepare the statement.
$statement = $db->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id");
//Bind the Value, binding parameters should be used when the same query is run repeatedly with different parameters.
$statement->bindValue(":id", $_GET['id'], PDO::PARAM_INT);
//Execute the query
$statement->execute();
//Fetch all of the results.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
//$result now contains the entire resultset from the query.
}
//In the case an error occurs, a PDOException will be thrown. We catch it here.
catch (PDOException $e) {
echo "An error has occurred: " . $e->getMessage();
}
You need to use PDOStatement::execute instead of PDO::query:
$foo_query = $sql->execute();
You may also bind all your params at once when calling execute:
$foo_query = $sql->execute(array(
':id' => $id
));
You should change it to:
$sql->execute();
if($r = $sql->fetch()) {
$title = $r["title"];
$body = $r["body"];
Try this:
$sql = $DBH->prepare("SELECT id, postdate, title, body
FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam (':id', $_REQUEST['id'],PDO::PARAM_INT);
$sql->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$title = $row["title"];
$body = $row["body"];
}