Script keeps showing array to string conversion mistake - php

I created an array and stored it inside a $_SESSION variable, now I want to include that array inside a MySQL select statement to get more infos depending on p, which is included in my URL. My code is included inside a HTML page, which is completely empty except for necessary HTML and of course session_start, so this is not the problem. The code looks like that:
<?php
$p = $_GET["p"];
var_dump($_SESSION['questions'][$p]);
include("../script/db_connect.php");
$p = $_GET["p"];
$select_right_question = "select * from questions where id = '{$_SESSION['questions'][$p]}'";
$question_infos = mysqli_query($con, $select_right_question);
while ($row = mysqli_fetch_assoc($question_infos)) {
echo $row["question"] . '</br>'
. $row["right_answer"] . '</br>'
. $row["answer2"] . '</br>'
. $row["answer3"] . '</br>'
. $row["answer4"];
}
mysqli_close($con);
?>
I already tested it and the main issue is the following line:
$select_right_question = "select * from questions where id = '{$_SESSION['questions'][$p]}'";
What is the correct way to include the SESSION variable here?

Disregarding the security issues with your code, and assuming $_SESSION['questions'][$p] is returning an array, you can modify your SQL statement to:
$select_right_question = "select * from questions where id = '{$_SESSION['questions'][$p]['id']}'";

Related

Inserting wrong data in to the database with $wpdb->insert

So hey guys!
I currently have a code that gets data from a custom table called wp_refundrequests, and prints them as a table to the page. On the page the admin can either Accept, or Deny the request by pressing a button on the side of each order. Denying the request just deletes the request from the table, but accepting should delete it from the current table and insert the information to the next table called "accepted requests".
The wp_refundrequests table contains customer's order that they want to refund.
The code that gets the info and prints it:
global $wpdb;
$requests = $wpdb->get_results("SELECT * FROM wp_refundrequests", ARRAY_A);
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Deny</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Accept</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
With my current code, the "Accept" button deletes it, and inserts information in to the new table, BUT the information that is inserted is wrong. It seems like it wants to either insert the latest data that had been inserted in to the wp_refundrequests table to the wp_acceptedrequests, or it keeps the data from the latest refund request and tries to insert that instead because for example as seen here(Sorry for the bits of Finnish as well):
If I were to click the "Accept" button on the above, older one, the query would still insert it like this:
So it basically inserts the info from the latest refund_request insert and inserts that instead of the one selected. However the one that had been selected still gets deleted from the table.
Here's the code that is triggered when the user clicks on "Accept"
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
/* Query to do whatever here */
$wpdb->print_error();
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->print_error();
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
I have to say I have no idea why it doesn't want to insert the selected request, please comment if there's something confusing, I'll try to clear it up then.
Thanks in advance!
You redefine $_SESSION with in foreach loop so at the end of foreach it will equal to the last one, pass each row parameter to it is accept link like this
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']."&custname=".$row['customer_name']."&prodname=".$row['product_name']."'>Accept</a></li></div>";
Then call it the same way you get $accept-ID
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_GET['custname'];
$prodname = $_GET['prodname'];
Note:Iuse my phone so make sure if it was a syntax error in the href part of the code
Please try like this and comment out the session variable.
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$accepted_requests = $wpdb->get_results("SELECT * FROM wp_refundrequests WHERE id = $accept", ARRAY_A);
if( !empty($accepted_requests) ) {
$insert = $wpdb->insert("wp_acceptedrequests", $accepted_requests);
if($insert) {
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
}
}

How to pass variables from one PHP file to another using HTML links?

//DB CONNECTION
$sql = "SELECT `city`,`country` from infotab";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["city"].$row["country"]"<a href='order.php'>order</a>"; }
Table output:
This code will select data. Additionally, there is reference to order.php on every line. When the user clicks on reference( <a href> clause), it opens order.php and there I need to know which row the user selected to work with these data.
Change the code to:
while ($row = $result->fetch_assoc()) {
echo $row["city"] . $row["country"] . "<a href='order.php?city=" . $row["city"] . "&country=" . $row["country"] . "'>order</a>";
}
In order.php you can then access these values by using the $_GET["city"] and $_GET["country"] variables which contain the values from your <a href> link on the previous page. For example, running echo $_GET["city"]; will output the city name.
Edit: As #Rizier123 pointed out, using a unique ID might be more prone to errors in case your database contains more than one entry for the same city or country. You should consider introducing an ID in your table structure and then using that in the link to order.php.

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

PHP: using $_POST within a loop

On one page I have a dynamically created form which has this element in it (note I have left out some stuff for clarity, eg: table and form elements):
$getallusers = "SELECT * FROM `ft_users`";
$usersstmt = $modx->query($getallusers);
while ($row = $usersstmt->fetch(PDO::FETCH_ASSOC)) {
echo "<td><input type='text' name='" . $row['userid'] . "' id='" . $row['userid'] . "' size='4'></td>";
}
On the form processing page I am trying to retrieve the values:
$getallusers = "SELECT * FROM `ft_users`";
$usersstmt = $modx->query($getallusers);
while ($rowuser = $usersstmt->fetch(PDO::FETCH_ASSOC)) {
$userpoints = trim($_POST["user_ids"][$rowuser["userid"]]);
}
If I do print_r($_POST); I get the array of data I sent in the form so I know the forms working OK. Its just the part converting the data into a variable:
$userpoints = trim($_POST["user_ids"][$rowuser["userid"]]);
Does anyone know a better way of doing this?
Change this in the first code block:-
while ($rowuser = $usersstmt->fetch(PDO::FETCH_ASSOC))
to
while ($row = $usersstmt->fetch(PDO::FETCH_ASSOC))
I think it has something to do with your POST retrieval. Exactly $_POST["user_ids"]; it should match whatever you have in your name='" . $row['userid'] . "'
Browse the page source and look it up

the data can't display in the form

about my system the university complaint..stud or staff can use this system to complaint.
first user fill the form complaint and submit after submit user can view the complaint.now the problem is the complaint can't display....
this code for user complaint(userCampus.php):
?php // ------------------------------------------------------PROCESS -------------------------- START. ?>
<?php
$page_title='userCampus';
if(isset($_POST['submit'])){
if($_POST['secname']){
//$sn=escape_data($_POST['secname']);
$sn=$_POST['secname'];
// echo '<br> sn is : ' . $sn;
}else{
$sn=FALSE;
$message .='<p>You forgot to select section name!</p>';
}
if($_POST['subject']){
//$s=escape_data($_POST['subject']);
$s=$_POST['subject'];
}else{
$s=FALSE;
$message .='<p>you forgot to enter subject!</p>';
}
if($_POST['comment']){
//$c=escape_data($_POST['comment']);
$c=$_POST['comment'];
}else{
$c=FALSE;
$message .='<p>you forgot to enter comment!</p>';
}
}
if($sn && $s && $c ){
$userid = $_SESSION['username'];
$groupid = $_SESSION['secname'];
$query=" INSERT INTO campuscomplaint (secname, subject, comment, nameuser, groupid, userid)" .
" VALUES (" . "'" . $sn . "','" . $s . "','" . $c . "','" . $nameuser . "','" . $groupid . "','" . $userid . "')";
//echo 'query is : ' . $query . '<br>';
include "connectioncomplaint.php";
mysql_query($query);
echo'<p><b></b></p>';
include('done.php');
exit();
}
?>
<?php //------------------------------------------------ PROCESS ------------------------------------ end. ?>
<form action="<?php echo$_SERVER['PHP_SELF'];?>" method="post">
this code for view the complaint-userView.php(use for other page):
<?php //======================================================================================================================= PROCESS DATA ======================================================= START.
include "connectioncomplaint.php";
?>
<?php
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
//echo 'test : ' . $subject;
//Tarik data dari sini
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
//echo 'QUERY DETAIL :' . $queryDetail . '<br>' ;
$resultDetail = mysql_query($queryDetail);
//echo 'RESULT DETAIL :' . $resultDetail + 0 . '<br>' ;
$detail = mysql_fetch_array($resultDetail);
//echo $detail . '<br>';
//echo 'detail subject is : ' . $detail['subject'] . '<br>';
//echo 'detail comment is : ' . $detail['comment'] . '<br>';
//echo $detail[$x] . '<br>';
?>
i hope u all can help me....becoz i zero php.......
Let's see if we can check everything in on snip of code:
Paste the debugging code right after the line:
$detail = mysql_fetch_array($resultDetail);
Debugging code:
echo '<pre>';
echo '$userid = '.$userid."\n";
echo '$secname = '.$secname."\n\n";
echo 'Query: '.$queryDetail."\n\n";
echo 'Query results:'."\n\n";
print_r($detail);
echo '</pre>';
die();
That should make it clear where your problem is.
Also you should understand why you need to use mysql_real_escape_string() It's very important to make sure people don't do bad things to your website. Never send anything that can be changed by the user (such as GET or POST data) straight to a database without at least using this function. This escapes characters that would otherwise allow them to change your query (making it do something you don't want). To learn more about this google "sql injection attack"
one thing, from my experience. if something wrong with your query, just try it on mysql. ran your query in sql, and instead of your variables put some values, so you can easaly see what is your problem.
Looks like you forgot a $ sign before secname and you don't sanitize variables going to the query. So, try make it this way:
<?php
include "connectioncomplaint.php";
$userid = mysql_real_escape_string($_GET['userid']);
$secname = mysql_real_escape_string($_GET['secname']);
//Tarik data dari sini
$queryDetail = "SELECT * FROM campuscomplaint " .
"WHERE userid = '$userid' AND secname = '$secname'";
$resultDetail = mysql_query($queryDetail) or trigger_error(mysql_error()." in ".$queryDetail);
$detail = mysql_fetch_array($resultDetail);
?>
It looks you're not using a primary key on your campuscomplaint table, and using the various data fields as the identifier.
Since you say the data's inserted fine, you have to look at how you're retrieving it:
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
and then using these as your WHERE clause in the SQL query:
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
For one, this is vulnerable to SQL injection, and any $subject or $comment that contains single quotes will break the query. You are not checking to see if the query succeeded by calling mysql_error() after the mysql_query() call.
Also consider that you're retrieving these record "identifiers" from a GET query. These do have a limited length (different for various browsers). What if someone's comment is 10 kilobytes of data, but the browser will only send 1024 characters? Even if the database query succeeds, it will return no data because the comment fields will never match.
Let's say that the query string is limited to 100 characters (just for example purposes). You generate a list of complaints that looks something like this:
View complaint
Now remember, our query string is limited to 32 characters, so when the user clicks on the link, this is what will be sent to the server:
GET http://www.example.com/viewcomplaint.php?userid=7&secname=12&subject=This class sucks!!!&comment=Who hired this professor? He doesn't know a
and you'll end up with the following "identifiers"
$userid= 7;
$secname = 12;
$subject = "This class sucks!!!";
$comment = "Who hired this professor? He doesn't know a";
Notice how the $comment has been cut off. It will never match what is stored in the database, so your retrieval query will fail. Furthermore, notice that there is a single quote in it (doesn't). Inserting $comment into your query verbatim will now cause an SQL syntax error because of the imbalanced single-quote.
Add an auto_incrementing primary key field to your campuscomplaint table, like this:
ALTER TABLE campuscomplaint ADD id int unsigned not null auto_increment primary key;
and then all your complains can be identified by a single number, and you can retrieve them like this:
$id = (int)$_GET['id']; // force $id to be a number. better than just blindly using the value in a query
$query = "SELECT * FROM campuscomplaint WHERE id = $id;";
$result = mysql_query($query);
if (mysql_error()) {
// did the query fail? Say why!
die("MySQL query failed! Error cause: " . mysql_error());
}
etc....
The use of a numeric identifier will easily keep your query string very short (unless the people registering complaints file so many you get up into numbers hundreds or thousands of digits long).

Categories