Uknown column error i have tired multpul things - php

Im getting a Unknown column error and i cant seem to find a topic that seems to help me.. here the code but when i seem to remove the WHERE username = $user in the $query or replace $user with a quote it seems to work just fine. (FYI Im like a total noob at php)
<?PHP
$id = "";
$username = "";
$email = "";
$nick = "";
$isMod = "";
$rank = "";
$joinDate = "";
$ip = "";
$coins = "";
$curHead = "";
$curFace = "";
$curNeck = "";
$curBody = "";
$curHands = "";
$curFeet = "";
$curPhoto = "";
$curFlag = "";
$curColor = "";
$db = mysql_connect("localhost","root","");
mysql_select_db("opencp", $db);
$user = $_GET['user'];
$query = "SELECT * from game_users WHERE username = ". $user. "";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
echo "<?xml version=\"1.0\"\n";
echo "<products>\n";
while($line=mysql_fetch_array($result)){
echo "<item>" . $line['id'] . "</item>\n";
echo "<item>" . $line['username'] . "</item>\n";
echo "<item>" . $line['email'] . "</item>\n";
echo "<item>" . $line['nickname'] . "</item>\n";
echo "<item>" . $line['ismoderator'] . "</item>\n";
echo "<item>" . $line['rank'] . "</item>\n";
echo "<item>" . $line['joindate'] . "</item>\n";
echo "<item>" . $line['ips'] . "</item>\n";
echo "<item>" . $line['coins'] . "</item>\n";
echo "<item>" . $line['curhead'] . "</item>\n";
echo "<item>" . $line['curface'] . "</item>\n";
echo "<item>" . $line['curneck'] . "</item>\n";
echo "<item>" . $line['curbody'] . "</item>\n";
echo "<item>" . $line['curhands'] . "</item>\n";
echo "<item>" . $line['curfeet'] . "</item>\n";
echo "<item>" . $line['curphoto'] . "</item>\n";
echo "<item>" . $line['curflag'] . "</item>\n";
echo "<item>" . $line['colour'] . "</item>\n";
}
echo "</products>";
mysql_close($db);
?>

Change it to,
$query = "SELECT * from game_users WHERE username = '". $user ."'";
$result = mysql_query($query);
You should start with PHP Strings.
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

username is a string so it should be in single quotes.
$user = $_GET['user'];
$query = "SELECT * from game_users WHERE username = '". $user. "'";
$result = mysql_query($query);

There are a couple answers here already but I thought I'd point out that since your string is in double quotes you can make it less confusing by not using the concatenation (period) style:
$query = "SELECT * from game_users WHERE username = '$user ' ";
Variables are replaced inside double quotes in php, but not within single quoted strings.

Related

Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54

I am trying to get this php code to run. I have made it output the table, however, I am getting this error:
Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54
I have been able to use the $row to get the values of it before and even reassigned it later to make sure that it wasn't only executing in WHILE. I have no clue what is going on there. Line 54 is the line:
foreach ( $row as $each)
Here is the file that I am using it in. Any help is appreciated on
a) how to make this file better and
b) getting the whole foreach statement working.
Thank you in advance!
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$inarray = array();
$outarray = array();
$current = array('in'=>$inarray,'out'=>$outarray,'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
You need to check if the argument passed through foreach is an array.
This can be done by using the function is_array()
if (is_array($variable)) {
foreach ($variable as $item) {
}
}
Unless I am missing something, which I do a lot, it seems to me that you've already iterated through your SQL results here,
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
which means that the data is no longer available because you are not using a prepared statement in order to reuse it. You should be able to run another query for the foreach.
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$row = $result->fetch_array();
foreach ( $row as $each) {
//your existing code.
}

Why am I getting white spaces from this function?

I made a function that loops through all the posts in database and echo them. But there's a slight problem. I am getting whitespace between the name (title of the post) and the content, its like two lines or so. I want reason for this and solution. Thanks.
function read_all_posts(){
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'website';
$con = mysqli_connect($host, $username, $password, $database);
$query = "SELECT * FROM posts";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<br>" . $row['content'] . "<br />" . "<i>" . $row['author'] . "</i>";
echo "<br>";
}
}
try,
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<p>" . $row['content'] . "</p>" . "<p><i>" . $row['author'] . "</i></p>";
}

Pesky Apostrophes in Database results

Okay... to make a long story short... here is my code...
<?php
$con = mysql_connect($db_server_name,$db_username,$db_password);
if (!$con)
{
echo "0";
}
mysql_select_db("" . $db_database_name . "", $con);
$result = mysql_query("SELECT * FROM sched_posts
WHERE user_id='$user_id'");
while($row = mysql_fetch_array($result))
{
$post_id = $row['ID'];
$post_year = $row['post_year'];
$post_month = $row['post_month'];
$post_day = $row['post_day'];
$post_hour = $row['post_hour'];
$post_minute = $row['post_minute'];
$post_privacy = $row['post_privacy'];
$post_message = $row['post_message'];
echo " {";
echo " id: " . $post_id . ",";
echo " title: ' " . $post_message . "',";
echo " start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo " allDay: false";
echo " },";
}
?>
When returning results, the post_message sometime's comes back with apostrophes in it. How can I get those results to appear as \' instead of just ' (in other words... with a backslash in front of it)?
PS.. I know some of this code looks unnecessary but please try to ignore that.... this is only setup this way for some testing that i am doing for facebook SDK results (for example, the identifiers inside of the WHILE statement).
The problem is, the returned apostrophes are causing the entire thing to go loopy... you know what i mean.
If you convert all those "date partial" columns into a timestamp, you can simply use json_encode():
$ts = mktime($post_hour, $post_minute, 0, $post_month, $post_day, $post_year);
echo json_encode(array(
'id' => $row['ID'],
'title' => $row['post_message'],
'start' => date('r', $ts), // <-- that's a string now
'allDay' => false,
));
JavaScript has no problems using rfc822 formatted dates.
To add backslashes, the function addslashes() would work for this:
http://php.net/manual/en/function.addslashes.php
To encode JSON 100% reliably (especially for fields like this that you can't predict/expect certain values/input), it would be best to use json_encode():
while($row = mysql_fetch_array($result))
{
$post_id = $row['ID'];
$post_year = $row['post_year'];
$post_month = $row['post_month'];
$post_day = $row['post_day'];
$post_hour = $row['post_hour'];
$post_minute = $row['post_minute'];
$post_privacy = $row['post_privacy'];
$post_message = $row['post_message'];
$dateString = ''; // computed date string...
echo json_encode(array("id"=>$post_id,"title"=>$post_message,"start"=>
$dateString,"allDay"=>false));
}
The json_encode() function is designed to generate JSON data but, since JSON is a subset of JavaScript, it's the best alternative to generate dynamic strings. Here's a use example:
<?php
$post_id = 314;
$post_message = <<<EOM
Jim "Big Boy" O'brian wrote:
<strong>Hi</strong>
EOM;
$post_year = 2013;
$post_month = 10;
$post_day = 9;
$post_hour = 17;
$post_minute = 4;
echo "{";
echo " id: " . $post_id . ",";
echo " title: " . json_encode($post_message) . ",";
echo " start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo " allDay: false";
echo "},";
... that produces:
title: "Jim \"Big Boy\" O'brian wrote:\r\n\r\n<strong>Hi<\/strong>\r\n"
Please note you have to omit the surrounding quotes; the function adds them for you.

Output stops after a while loop, without using "or die()"

I know there is another question with the same topic, but that question involves the or die() statement. I have the same problem, but i'm not using a or die() statement on my while loop. The answer is probably pretty obvious, but i can't figure it out.
$Dates = "1";
$Select = $mysqli->query("SELECT * FROM ----");
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
$Vals = $Get->fetch_assoc();
if ($Vals != "") {
$TimeIn = $Vals["Time_In"];
$TimeIn2 = explode(":",$TimeIn);
$TotIn = ($TimeIn2[0]*60)+$TimeIn2[1];
$TimeOut = $Vals["Time_Out"];
$TimeOut2 = explode(":",$TimeOut);
$TotOut = ($TimeOut2[0]*60)+$TimeOut2[1];
$TotTime = ($TotOut - $TotIn)/60;
$TotalTime = floor($TotTime) . " Hours " . ($TotTime-floor($TotTime))*60 . " Minutes";
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td>" . $TimeIn . "</td><td>" . $TimeOut . "</td><td>" . $TotalTime . "</td></tr>";
}
if ($Vals == "") {
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td colspan='3' style='background-color: rgba(0,0,0,0.25)'>Did not Attend</td></tr>";
}
}
Anything i put after the while loop, doesn't get executed, even though the while loop only executes 2 times like it is supposed to...
Any ideas are appreciated
This is the problem:
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
When there are no more records, $Dates will be empty (NULL) so the next line will lead to a fatal error.
You can change it to:
while ($Dates = $Select->fetch_assoc()) {
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");

mysqli_fetch: returns one row

I am making a private message system and I'm using the mysqli_fetch() function in a while statement to return all the rows associated with the query. However, PHP only returns the last row in MYSQL.
Here is my code:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$Val = $_POST['ID'];
$Get = 'SELECT * FROM CMessages WHERE PID="'.$Val.'"';
$Username = $_SESSION['Username'];
$Admin = $_SESSION['Admin'];
if($Result = $Connect->query($Get))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$Msg = $Row['Msg'];
$Date = $Row['Date'];
$ID = $Row['ID'];
if($User == $Username)
{
$MText['T'] = '<div id="Msg">' . $User . ' : ' . $Msg . ' - ' . $Date .' - <a class="TLink" href="MDelete.php?ID='.$ID.'">Delete</a></div>';
}
elseif(isset($Admin))
{
$MText['T'] = '<div id="Msg">' . $User . ' : ' . $Msg . ' - ' . $Date .' - <a class="TLink" href="MDelete.php?ID='.$ID.'">Delete</a></div>';
}
else
{
$MText['T'] = '<div id="Msg">' . $User . ' : ' . $Msg . ' - ' . $Date .'</div>';
}
}
}
echo json_encode($MText);
?>
It returns all rows but , in the while loop, you are always overwriting the $MText variable. Therefore only the last one will be displayed with json_encode.
Maybe you meant to write $MText['T'][] instead of $MText['T'].

Categories