Replace variable with query - php

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

Related

Listing username with bid items - 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 . "')";

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.

Update/Insert into mysql query

I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.

How do I replace record if one variable has changed?

I am taking a calendar feed with a PHP file and I need to compare it to my database. If the $lastEdited variable is different than what is in the database, I need to change the record. I'm really new to SQL, so I'm not sure what to do. I just have Date_Edited set as a VARCHAR so I just need to compare the strings. I have this:
$query = "SELECT * FROM myTable WHERE Event_ID='$id'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
mysql_query("INSERT INTO myTable (Event_ID, Date_added, Date_edited, Title)
VALUES ('$id', '$dateAdded', '$lastEdited', '$title')");
}
How do I compare $lastEdited to Date_edited and change the row if they are different?
you need to do something like
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($lastEdited != $row['Date_added']){
# run update query
mysql_query("update myTable set
// here insert all update fields you need like
Date_added = '$dateAdded', Date_edited = '$lastEdited' , Title = '$title'
WHERE Event_ID='$id' ");
}
You probably want to use the UPDATE statement.

Get a column value (like id) after mysql INSERT

Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.

Categories