Listing username with bid items - PHP - php

I'm fairly new to PHP and I'm trying to make a simple auction website. I think I've run into my first problem.
What I'm trying to do is let a registered user add an item to the auction. I can do this just fine. However, I also need to keep track of the user that put the item up for bidding. I thought I could get the accountid by inserting the accountid from the current session into my table, but I keep getting an error saying accountid is an unknown column in my field list.
Here is the code where I create the table.
$sql = "CREATE TABLE biditems (
itemid INT(100) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
accountid INT(100),
biditem VARCHAR(30) NOT NULL,
biddesc tinytext
)";
And to add the items.
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('$accountid', '$item', '$description')";

Your query looks fine. I have also tested it.
Did you double check that the structure of your table is correct?
If you can insert a row via phpMyAdmin or the MySQL Workbench try this and afterwards run a select query like
$rows = "SELECT * FROM biditems";
while ($row = mysql_fetch_array($rows)) {
var_dump($row);
}
Something like this just to make sure.

You should make some sql injection escape first. And if you did it - you should add the variables properly. I did not wrote you some injection escape. You can see sprintf instructions for example.
<?php
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('" . $accountid . "', '" . $item . "', '" . $description . "')";

Related

Replace variable with query

I am pretty new to using mysql and variables in php.
I have this code
mysql_query("INSERT INTO `forum_threads` (`name`, `byid`, `cid`,
`content`, `time`, `lastreplied_time`, `lastreplier_id`) VALUES
('{$title}', '{$uid}', '{$cid}', '{$content}', '" . time() . "', '" .
time() . "', '{$uid}');") or die(mysql_error());
In my php file, I want byid to be the value of id in my table forum_users. So can I replace {$uid} with something that will get the value from forum_users. Because I don't think {$uid} is working correct.
I found this code
/* Non-existant forum account */ final public function
createForumAccount($uid) {
$getHabboUser = mysql_query("SELECT * FROM
`users` WHERE `id` = '{$uid}' LIMIT 1");
I assume that the function of that code is to get the {$uid} equal the id from the users table, I want to make the {$uid} to equal the id from the forum_users table.
Then I found this code:
final public function getUserData($uid, $var) {
if($this->checkForAccount($uid) == true) {
$check = mysql_query("SELECT `{$var}` FROM `forum_users` WHERE `uid` = '{$uid}' LIMIT 1") or die(mysql_error());
return mysql_result($check, 0);
}
}
That code wants the {$uid} to equal forum_users id. And that is exactly what I want, but it doesn't equal that, it equals the id from the users table instead, I assume it might collide with eachother or something.
How can I solve this? Can I replace {$uid} in my first code, so byid is selected instantly from forum_users? Can I make a new variable that equals forum_users.id?
First of all this sql query makes no sense. However I am also not sure your question either. If your wanting to change byid to id in your table then you must alter the table. But here is a cleaner version of your sql query.
try:
mysql_query("INSERT INTO forum_threads SET name=\"".$title."\",byid=\"".$uid."\",cid=\"".$cid."\",content=\"".$content."\",time=\"".time()."\",lastreplied_time=\"".time()."\",lastreplier_id=\"".$uid."\" WHERE id=\"".$uid."\" LIMIT 1") or die("Error: ".mysql_error());
//You Change ID to byid
to change byid to ID
mysql_query("ALTER TABLE `forum_threads` CHANGE `byid` `id` int NOT NULL")or die("Error: ".mysql_error());
// this will change the column byid to id
Just Remember Mysql_connect() and mysql API are old and not used after php 7 so start to learn mysqli api
http://php.net/manual/en/book.mysqli.php

MySQL INSERT query does not update the DB

attent table :
id int(11) primary key
userID int (11) forigen key from users table
date date
start_time text
end_time text
approv enum default 0
my query :
$sql = "INSERT INTO attent ".
"(id,userID,date,start_time,end_time,approv) ".
"VALUES ".
"('NULL','$userid','$date','$start_time','$end_time','NULL')";
$query = mysqli_query($db,$sql);
I got config.php file that help communicate with dB. I did a few insert queries before and all of them work just fine. I can not understand where is my mistake.
Write your query as below:-
"INSERT INTO attent(`id`,`userID`,`date`,`start_time`,`end_time`,`approv`)
VALUES(NULL,'$userid','$date','$start_time','$end_time',NULL)"
Try like this use back tick,because date is reserved word in mysql
$sql = "INSERT INTO `attent` ".
"(`id`,`userID`,`date`,`start_time`,`end_time`,`approv`) ".
"VALUES ".
"('','$userid','$date','$start_time','$end_time','')";
It's easier to understand what's going on if you will try to put such a query manually through e.g. phpMyAdmin
I don't know your table structure but try to skip id attribute as it's often autoincrementable. You can always skip the fields that is not set to NOT NULL.
Like that:
$sql = "INSERT INTO `attent` ".
"(`userID`,`date`,`start_time`,`end_time`,`approv`) ".
"VALUES ".
"('$userid','$date','$start_time','$end_time','')";

MYSQL: Saving various instances of players

I host multiple servers for multiplayer games and I am requiring some help with creating a PHP MySQL script.
I have made scripts for the game servers that output a few variables to a php script. These variables include the player name, a GUID number (Game User ID) and a couple other unimportant things. These are sent to the php script every time a player joins the server.
Anyway what I basically need it to do is every time a player joins the server it saves the player name, guid and join date/timestamp to a row in a MySQL table. The player will always have only one GUID code, which is sort of like their cd-key. What I have at this current time:
if ( $action == "save")
{
$name = mysql_real_escape_string($_GET['name']);
$guid = mysql_real_escape_string($_GET['guid']);
}
mysql_query("INSERT INTO `players` (`name`, `guid`) VALUES ('$name', '$guid') ON DUPLICATE KEY UPDATE `last_joined`=CURRENT_TIMESTAMP")or die(mysql_error());
echo "-10";
die();
Now, this works great as it is. But what I need it to do is; if the player comes on the server with a different name, it will log that instance into a new row and if they come on again with the same name it will update the same row with the current time stamp. And for instance, if they change their name back to the first name they use it will update the row that has that name recorded with the current time stamp.
The only thing I have tried is making the 'name' column, a primary key and on a duplicate entry it would update it. However if I did that and another player came on the server with the same name it would just update the last player's data.
So it needs to record every username a player uses.
There's probably quite a simple solution but I've never had the time to learn to MySQL and I need this done soon.
Thanks for any help.
Make the GUID the primary unique key.
Then instead of just inserting the row, check if that guid exists in the database first and then if it does, update the row. If it doesn't then you can insert it.
You can take a shot for this:
$guid = mysqli_real_escape_string($conn, $_GET["guid"]);
$name = mysqli_real_escape_string($conn, $_GET["name"]);
if (!empty($guid) && !empty($name)) {
//Check if the user exists
$sql = "SELECT COUNT(*) AS cnt FROM players WHERE guid = " . $guid;
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($res);
if ($row['cnt']) {
//If yes, update
$sql = "UPDATE players SET `last_joined` = NOW()
WHERE `guid` = " . $guid;
} else {
//If no, insert
$sql = "INSERT INTO players (`guid`, `name`, `last_joined`)
VALUES (" . $guid . ", '" . $name . "', NOW())";
}
mysqli_query($conn, $sql);
echo "-10";
die();
} else {
echo 'Missing parameter';
die();
}
NOTE:
I am using mysqli fucntions, because mysql functions are deprecated. You can use PDO also.

mysql_insert_id not working

Apologies for the vague title, here's my problem:
The goal of my code is to insert a new row into a table that has an auto-increment field. After the insert, I want to get the value of the auto-increment field that has just been generated.
Here's my table defintion:
CREATE TABLE `EventComments` (
`CommentID` int(11) NOT NULL AUTO_INCREMENT,
`EventID` int(11) NOT NULL,
`OwnerID` int(11) NOT NULL,
`Comment` varchar(512) NOT NULL,
`DateTime` datetime NOT NULL,
PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;
I'm trying to get the value of the CommentID field.
So, here is the php code that issues the insert query and then attempts to get the CommentID value.
<?php
session_start();
ob_start();
include_once 'lib/functions.php';
if(isset($_SESSION['uid'])) {
$eventID = $_GET['evid'];
$ownerID = $_SESSION['uid'];
$comment = $_GET['comment'];
$comment = trim($comment);
$dateTime = date('Y-m-d H:i:s');
$db_connection = database_connect();
if($eventID != null && !empty($comment)) {
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";
mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));
$id = mysql_insert_id();
$commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime, $id);
echo $commentHtml;
}
}
ob_end_flush();
?>
This code issues the following error in the php logs:
mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...
I also tried explicitly passing the database link. But that gives the following error:
mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...
As a final note, the insert query works. It is definitely inserting a new row with the expected data!
Any insight here would be appreciated!
Thanks
You are using the mysqli extension to connect and run your query, but then you use the mysql (notice the lack of i at the end) extension to get your inserted id, that can't work. While they are both extensions that provide access to mysql, they are also two very different libraries and can't share a connection between each other.
For the record, mysqli is the one you should be using, mysql is the "old" version that does not support new features of mysql >= 4.1
In other words, the solution is to use mysqli_insert_id()
Also, please escape your parameters properly, you can't put the content of $_GET and $_POST variables inside your query unsecured like that. At the very least use mysqli_real_escape_string()
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . mysqli_real_escape_string($eventID)." [...]
For more infos on this, have a look to the numerous questions on this subject, for example this one: How to properly escape a string via PHP and mysql
You probably want to use the mysqli extension equivalent: mysqli_insert_id()
It might work as it is by passing the connection resource but even if it did, it's not good to mix methods from two separate connection classes:
$id = mysql_insert_id($db_connection);
DATETIME is a Data Type in MySQL that's why INSERT query is not working. Use backtick ` instead.
$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";

How to get the primary key which is an auto-increment for the row just entered in PHP?

I have a SQL query like
$result = mssql_query("INSERT into CALLER
( status, media, media_2, first_name, last_name, street_address, city,
state, zipcode, home_phone_no, mobile_phone_no,email, problem,
medical_condition, comments, updated_date )
VALUES
('CALL', '$media', '$media_2','$fname','$lname', '$street_addr', '$city',
$state','$zip', '$phone_alt', '$phone','$email','$problem','$mc',
'$comments',GetDate() ); ");
The primary key for the table CALLER is an auto-increment. How can I get the Primary Key of the row just inserted after this query ?
Correction: use this.
$query = mssql_query("SELECT ##IDENTITY");
$row = mssql_fetch_assoc($query);
Well if you have any CANDIDATE KEY in the table, you can use that to retrieve the last inserted row.
Say you have a candidate key consisting of columns status, email and problem.
Then you can execute a query like this just after your insert.
$query = "SELECT id FROM CALLER
WHERE
status = '" . $status . "'
AND email = '" . $email . "' AND
problem = '" . $problem . "'";
mssql_query($query);
This will return the id for that entry.
Update
I just saw this in a comment by Mikael to Femi's Answer, you can use SCOPE_IDENTITY()
It returns the las insert id for the current connection in current scope. So it should work for you even if multiple instances do inserts which are interleaved.
So you can simply do this after the insert
$res = mssql_query('SELECT SCOPE_IDENTITY()');

Categories