I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.
Related
I am trying to update the store column by adding new item (string) to the end of the column,
But what happens is the new item is added twice at the end of the column, This is the code:
$query = "SELECT * FROM users";
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$item = 'item_name';
$store = $row['store'];
$newstore = $store . '|' . $item;
echo 'newstore : ' . $newstore . '<br>'; // It looks normal : store|item
$sql = "UPDATE users SET store='" . $newstore . "' WHERE username='" . $row['username'] . "'";
$conn->query($sql);
}
In in the database I find: store|item|item
Rather than reading the entire table and looping through it with PHP, run just a single UPDATE query to concatenate the extra data onto the column.:
$item = 'item_name';
$query = "UPDATE users SET store=concat(store,'|','$item')";
$result = $conn->query($query);
Note: this form is potentially open to SQL injection if you can't trust the value in $item. You'd do better to use a prepared query if that's the case.
I have issue where obj->num_rows constantly returns 1 Heres my code:
$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets->num_rows . '</td></tr></table>';
$open_tickets->close();
$_SESSION['user'] is currently dextermb
As you can see in my SQL table, there are 2 tickets with the name dextermb, so why does the code always return 1?
You are getting the number of rows returned - of course, this is only ever going to be 1. You probably want to get the value that is returned rather than the number of rows.
Try this
$open_tickets = $con->query("SELECT * FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . count($open_tickets) . '</td></tr> </table>';
$open_tickets->close();
The query will return the count, just use the value.
Try:
$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets . '</td></tr></table>';
$open_tickets->close();
Try this:
$stm = $con->prepare("SELECT COUNT(*) as total FROM support_tickets WHERE Username = :username");
$stm->bindParam(':username', $_SESSION['user']);
$stm->execute();
$row = $res->fetch();
echo '<table><tr><th>Open Tickets</th><td>' . $row->total . '</td></tr></table>';
Note prepare and bindParam methods. This way you avoid SQL Injection.
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I grabbed this piece of code off the Internet and modified it slightly to fit my needs but it doesn't work and I don't know why. I'm sure I've overlooked something but I don't know enough about PHP to know what I'm doing wrong. The uid is showing up, but nothing else. I'm just trying to get information from the MySQL data based on the user's session id. I checked the database to make sure that the uid that shows matches the data -- it does.
<?php
include("connect.php");
session_start();
$uid = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
if ($result) {
echo "Connect"; } else
{ die('Invalid query: '.mysql_error()); }
$info = mysql_fetch_array($result);
echo "<br>ID: ", $uid;
echo "<br>Full Name: " .$info['full_name'] ;
echo "<br>User Name: " .$info['user_name'] ;
echo "<br>";
?>
p.s. - Yes, I know that mysql_query (and other syntax like it) has been deprecated.
$result = mysql_query("SELECT * FROM users WHERE id = '" . $uid . "'"); // not ' . $uid . '
NOTE: You were searching for . ID . not actual ID
Query should be as
$result = mysql_query("SELECT * FROM users WHERE id = $uid ");
Assuming id is int in the table
You had
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
^.... ^.... was the issue.
I am trying to use the result of one mysql query in another mysql query, but I'm obviously doing something wrong. This is what I have:
<?php
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$panel = mysql_fetch_array($result);
?>
And then I want to use that in this bit:
<?php
if(!empty($_POST[p_length_mm]) && !empty($_POST[p_width_mm]) && !empty($_POST[p_aperture]))
{
$sql3="INSERT INTO estimateDescribesPanelProduct (estimate_no, panel_product_no, quantity)
VALUES ('$_GET[estimate_no]','$panel','$_POST[p_quantity]')";
if (!mysql_query($sql3,$con))
{
die('Error: ' . mysql_error());
}
}
?>
The query is basically working in that it is inserting the posted estimate_no and quantity into the DB, but not the correct panel_product_no (it just inserts '0'). How can I get it to insert the $result value?
P.S. I know that I should not be using mysql functions and I will not be in future, however I am so nearly finished with this project that at this point I am not in a position change.
Your are basicly copying content from one table to another.
Wy not use the MySQL INSERT .. SELECT syntax?
as #Dmitry Makovetskiyd wrote, mysql_fetch_array() returns a resource, not manipulatable results.
For example:
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$resource = mysql_fetch_object($result);
You need to add in:
$panel = $resource->'panel_product_no';
You can then continue with your second query.
Note the change from mysql_fetch_array() to mysql_fetch_object() - as your query suggests you are only retrieving a singular value from the table (assuming there is only a singular panel with the specified length, width, veneer type and lipping), the object method will work fine.