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.
Related
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i would love if any one could help me out with this issue.
The config.php file which is included works fine, and the database loads fine.
It's just about echoing stuff out of the database when connected with an Included file.
How would i do that the simplest cleanest way?
<?php
include 'config.php';
$username = $_COOKIE["ava_username"];
$user_id = $_COOKIE["ava_userid"];
$useridquery = mysql_query("SELECT id FROM ava_users WHERE username=$cookie");
if (isset($_COOKIE["ava_username"])) {
$result = mysql_query("SELECT points FROM ava_users WHERE username=$username");
echo "Cookie is enabled, and User status login is 0<br>";
echo "User ID: ". $user_id . "<br>";
echo "User Name: " . $_COOKIE["ava_username"]. "<br>";
while ($row = mysqli_fetch_array($result))
{
echo $row['points'] . " and Joined " . $row['joined'];
echo "<br>";
}
}
?>
You have mixed up mysql_* with mysql_i*
$useridquery = mysql_query("SELECT id FROM ava_users WHERE username=$cookie");
above line contains wrong query (need to use quotation )and seems that $useridquery is unused. this line should be like this:
$useridquery = mysqli_query("SELECT id FROM ava_users WHERE username='$cookie'");
same wrong query in this line :
$result = mysql_query("SELECT points FROM ava_users WHERE username=$username");
should be :
$result = mysqli_query("SELECT points FROM ava_users WHERE username='$username'");
try this:
include 'config.php';
$username = $_COOKIE["ava_username"];
$user_id = $_COOKIE["ava_userid"];
$useridquery = mysqli_query("SELECT id FROM ava_users WHERE username='$cookie'"); //add quotation in variable
if (isset($_COOKIE["ava_username"])) {
$result = mysqli_query("SELECT points FROM ava_users WHERE username='$username'"); //add quotation in username variable
echo "Cookie is enabled, and User status login is 0<br>";
echo "User ID: ". $user_id . "<br>";
echo "User Name: " . $_COOKIE["ava_username"]. "<br>";
while ($row = mysqli_fetch_array($result))
{
echo $row['points'] . " and Joined " . $row['joined'];
echo "<br>";
}
}
You are mixing between mysql and mysqli .
Try this:
<?php
include 'config.php';
$username = $_COOKIE["ava_username"];
$user_id = $_COOKIE["ava_userid"];
$useridquery = mysqli_query("SELECT id FROM ava_users WHERE username=$cookie");
if (isset($_COOKIE["ava_username"])) {
$result = mysqli_query("SELECT points FROM ava_users WHERE username=$username");
echo "Cookie is enabled, and User status login is 0<br>";
echo "User ID: ". $user_id . "<br>";
echo "User Name: " . $_COOKIE["ava_username"]. "<br>";
while ($row = mysqli_fetch_array($result))
{
echo $row['points'] . " and Joined " . $row['joined'];
echo "<br>";
}
}
?>
You are mixing functions from the mysql library with functions from the mysqli. They aren't the same, and that won't work. Please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure. Use MySQLi or PDO instead.
Another problem: you use $cookie in your first query, but it looks like you mean $username. $cookie isn't defined. It doesn't look like you ever even use that query's results, though, so you could just take it out.
Another problem: you are wide open to SQL injection.
The problem is you are mixing two libraries (the mysql_*-family and the mysqli_*-family). You cannot use mysqli_fetch_array(...) with mysql_query(...).
Basically the mysqli_query will not work till both the parameters are included. Mysqli query requires 2 parameters $link = connection to the database and $sql = the sql query. So typically the mysqli_query is of the following format mysqli_query($link, $sql) . You can try as below
<?php
include 'config.php';
global $link; //where $link = mysqli_connect("DBserver", "DBuser", "DBpswd", "DBname")
$username = $_COOKIE["ava_username"];
$username = mysqli_real_escape_string($username);
$user_id = $_COOKIE["ava_userid"];
//if the id is an integer then instead of mysqli_real_escape_string use
$user_id = intval($user_id);
$sql = "SELECT id FROM ava_users WHERE username = '$username'";
$useridquery = mysqli_query($link, $sql);
if (isset($_COOKIE["ava_username"])) {
$sql = "SELECT points FROM ava_users WHERE username='$username'";
$result = mysqli_query($link, $sql);
echo "Cookie is enabled, and User status login is 0<br>";
echo "User ID: ". $user_id . "<br>";
echo "User Name: " . $_COOKIE["ava_username"]. "<br>";
while ($row = mysqli_fetch_array($result))
{
echo $row['points'] . " and Joined " . $row['joined'];
echo "<br>";
}
}
?>
However even this code is highly vulnerable to MYSQL injection. You should always use parameterized queries to get protection against 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);
}
This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL.
I've bolded the most pertinent section of code.
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
As for your id question...that's how ids work. They don't fill in gaps.
On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().
SELECT * FROM test ORDER BY Id DESC LIMIT 1
this script have to update things on every refresh but not working. lend me a hand
$yp = mysql_query("select id from yyy where twitterid = '$tid'");
$qq = "update yyy set twitterid = '$tid',
twitterkullanici = '$twk',
tweetsayisi = '$tws',
takipettigi = '$tkpettigi',
takipeden = '$tkpeden',
nerden = '$nerden',
bio = '" . mysql_real_escape_string($bio) . "',
profilresmi ='$img',
ismi = '$isim'
where id = '$yp'";
$xx = mysql_query($qq);
Looks like you are not getting the value out of the variable $yp.
You need to do
$row = mysql_fetch_row($yp);
then
id = '.$row[0] .'
in your update query
$yp - is a result of mysql_query (resource). You have to read id from database (mysql_fetch_array or mysql_fetch_row).
$yp = mysql_query("select id from yyy where twitterid = '$tid'");
if ($yp)
{
if ($row = mysql_fetch_array($yp,MYSQL_ASSOC))
$id = $row["id"];
}
Now use $id in WHERE clause.
To make debugging SQL easier in PHP add the following after to your mysql_query(0 call.
mysql_query($qq) or die("A MySQL error has occurred.<br />Your Query: " . $qq. "<br /> Error: (" . mysql_errno() . ") " . mysql_error())
Just make sure you remove it before you go into prod, as it can give useful info away to any hackers attempting Sql Injection.