I am using the following code to pull all language variables and values form a MySQL database and populate a form for editing:
function language() {
$settings = array();
$sql = "SELECT * FROM `languages`";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
while ($row = mysql_fetch_assoc($result)) {
?>
<div style="float:left;width:250px;padding-left:15px"><label><?php echo $row['id'];?></label></div><div style="float:left;margin-left:0px;"><input type="text" name="<?php echo $row['id'];?>" value="<?php echo $row['value'];?>" /></div>
<? php
}
}
I have a rudimentary function to save the changes made in the above form back to the database updating with any changes:
function save_language() {
$post = $_POST;
$out = array_shift($post);
// Mysql_num_row is counting table row
foreach($post as $key => $value) {
$sql = "UPDATE `languages` SET `value`='$value' WHERE `id`='$key'";
$result = mysql_query($sql);
}
if ($result) {
echo "Language Settings Updated";
}
}
This method works but it is very slow. I am new to coding and I am sure I am overlooking something simple that would speed up the saving process.
Your query actually shouldn't be working because the connection is out of scope of the function. The correct way to pass the connection would be through the function:
function language( $conn ) {
...
}
You should immediately stop using your code due to injection vulnerabilities as well as the deprecation of mysql_ functions. Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Depending on how many records you are updating and how many connections you are making, it may slow down your script.
If you wish to INSERT records, you need to be using prepared statements.
Also, I don't understand the commnet // Mysql_num_row is counting table row in your save_language function as you are not using the number of rows from the result anywhere.
Related
I am developing a game(c#) with database(mysql) and web service(php) to retrieving the data. The issue is the data management. There is a table on database with the name of items and it has some columns like id, item_name, item_description, item_prop, update_date, ownerId. I added 70 items to this table manually. The users can also add some items to this table or they can update the items they have already added in the game. My purpose is retrieving the whole affected rows of the table when the user is first logged in and save it as a json file in the game folder. After, read that file to fill the game environment with those items.
I try a way to achieve this. Firstly, i hold an updateDate variable in the game which is past like "1990-05-10 21:15:43". Second, i send this variable to the webservice as '$lastUpdateDate'; and make a query according to that variable at the database. select * from channels where update_date >= '$lastUpdateDate'; and write these rows in a json file as items.json. after that make a second query to retrieve the time and refresh the updateDate variable in the game. select select now() as 'Result';. In this way user would not have to get the whole table and write in json file every login process. So, it would be good for the performance and the internet usage. The problem occurs when the users update an item which is already added before. I can see the updated item, too with the first query, but I wrote it in json file twice in this way.
php code part of the getItems of my loginuser.php :
<?php
include './function.php';
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "root"; //in general is root
$password = ""; //use your password here
$dbname = "yourDataBaseName"; //your database
$phpHash = "yourHashCode"; // same code in here as in your Unity game
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
$op = anti_injection_register($_REQUEST["op"]);
$unityHash = anti_injection_register($_REQUEST["myform_hash"]);
if ($unityHash == $phpHash)
{
if($op == "getItems")
{
$lastUpdateDate = anti_injection_login($_POST["updateDate"]);
if(!$lastUpdateDate)
{
echo "Empty";
}
else
{
$q = "select * from items where update_date >= '$lastUpdateDate';";
$rs = mysql_query($q);
if (!$rs)
{
echo "Could not successfully run query ($q) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($rs) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
$arr = array();
while ($row = mysql_fetch_row($rs))
{
$arr = $row;
}
echo json_encode($arr);
}
mysql_close();
}
}
?>
So, how can i solve this problem? Or do you have any better idea for this approach. Help would be much appreciated. Thank you for your time.
So I'm not the best with PHP but everyone has to start somewhere.
I am wondering how I would go about taking all of the rows from a database, taking out the data from a certain column and outputting it in a certain way.
The reason I'm doing this is to make it show up with all the users registered on one page, sort of like a members page any forums would have.
I was thinking of somehow fetching the rows than putting the data into arrays than doing a foreach statement to print it out as each variable.
I'm not the best logical thinker but I will give a bit of database information below :)
This is an image of the structure of the database.
To show you guys that I am actually putting an effort into this, this is what I got so far with my terrible PHP skills ;)
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result)) {
$username=array($row['username']);
$email=array($row['email']);
$firstname=array($row['firstname']);
$lastname=array($row['lastname']);
$motto=array($row['motto']);
$bio=array($row['bio']);
}
foreach ($username as &$item) {
print $item;
}
The one reason this code wouldn't work is because than its just selecting a row of the person with the id that is equal to $userid. This means it would grab the row info, not the column info.
Not sure how to do this as I've only done stuff with rows so far in my PHP adventure, not so much with columns :(
The way it works is, each time you loop through using "while", you have a new set of information. Just display your stuff right there. It's way easier than you think, which is why you have commenters complaining.
But DON'T use the mysql_* functions. Use mysqli or PDO. I know that there are tons of examples out there using mysql_*, but that's because they're either old examples or bad ones. Don't use it. I have taken an example from the PHP manual and adjusted it for you.
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli_query($link, "SELECT * FROM users ORDER BY username");
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$username=$row['username'];
$email=$row['email'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
$motto=$row['motto'];
$bio=$row['bio'];
//display your row of user information here
echo "<div>";
echo $username; //etc.
echo "</div>";
}
mysqli_free_result($result);
}
mysqli_close($link);
So I'm trying to write a temp way to login to the admin panel using an if else statement while I read up on PDO. If someone could tell me where the error lies here it would be much appreciated.
I've updated my code after looking around a little bit, but I still have the issue of nothing showing up where my code belongs and pulling the information it should.
<?php
$admin = $_SESSION['admin_login'];
$con=mysql_connect("$server","$user","$pass");
if
(!$con)
{
die('Could not Connect' .mysql_error());
}
mysql_select_db($webdb, $con);
$result=mysql_query("SELECT * FROM permissions WHERE username= '$admin' ");
$row = mysql_fetch_assoc($result);
if ($row['permissions']=="3")
{
echo 'Admin Panel';
}
elseif ($row['permissions']=="1")
{
echo 'include acp_error.php';
}
?>
Is what I've updated to; Does anyone see any issue here?
mysql_query returns a statement HANDLE, not the value(s)/row(s) you're trying to select. YOu need to FETCH a row of data to be able to get the values you need to compare.
$result = mysql_query(...) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['somefield'] == 3) {
...
}
Please note that things like
"$webdb"
are pointless cargo-cult programming. A simple
$webdb
is all that's needed for such things. There is not point in creating a new string, whose sole contents are the contents of a variable - just use the variable itself.
As well, note that you're vulnerable to SQL injection via that $_SESSION value you're using in the query. If that's a text value, and contains user-supplied data, your server is trivial to pwn.
I'm doing a transaction with PHP and MySQL. Using PHPMyAdmin I'm inserting queries into my University DB, where I'm supposed to use transactions in some tables. So far I've made this code for my Staff transactions, but my problem is how can I get the information inserted in addStaff.php so I can use it as a query on this code? right where it says //values();
<?php
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
function rollback()
{
mysql_query("ROLLBACK");
}
mysql_connect("localhost","username", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query = "INSERT INTO Staff (id,name,position,phone,email,roomNumber,dnumber)"
//values();
begin(); // BEGIN
$result = mysql_query($query);
if(!$result)
{
rollback(); // ROLLBACK
echo "You rolled back";
exit;
}
else
{
commit(); // COMMIT
echo "Transaction was succesful";
}
?>
This is maybe what you're looking for:
$new_row = mysql_insert_id();
$query = mysql_query("SELECT * FROM `Staff` WHERE `id`=".$new_row);
$r = mysql_fetch_assoc($query);
echo $r['name'];
will echo the inserted rows name.
Edit: This is a very very basic version of how to do things, before moving anything to production you need to read up on SQL Injection, Prepared Statements/Escaping User Input, XSS Attacks and many more vital parts of SQL query security
If I understand you question correct, you need to know how to prompt for data, accept it, and insert it into the database:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... connect to the database ...
$sometext = $_POST['textfield']; // retrieve the value from the form
$qsometext = mysql_real_escape_string($sometext); // make it safe for the query
$sql = "INSERT INTO mytable (textfield) VALUES ($qsometext);" // build the sql query
$result = mysql_query($sql) or die(mysql_error()); // run the query
}
?>
<html>
<body>
<form method="POST">
<input type="text" name="textfield"><input type="submit">
</form>
</body>
</html>
That's a barebones version of how to show a form, then insert the user's data into a database, the simply re-displays the form for more data.
I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.
Could someone look at my code and see where a problem could occur?
<?php
$title = "Edit News";
include("../includes/header.php");
include("../includes/database.php");
$done = false;
$expected = array('newstitle', 'newscontent', 'id');
if ($_GET && !$_POST) {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
else {
$id = NULL;
}
if ($id) {
$sql = "SELECT * FROM news WHERE id = $id";
$result = mysql_query($sql) or die ("Error connecting to database...");
$row = mysql_fetch_assoc($result);
}
// if form has been submitted, update record
if (array_key_exists('update', $_POST)) {
// prepare expected items for insertion into database
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
${$key} = mysql_real_escape_string($value);
}
}
// abandon the process if primary key invalid
if (!is_numeric($id)) {
die('Invalid request');
}
// prepare the SQL query
$query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id";
// submit the query
$done = mysql_query($query) or die("Error connecting to database...");
}
}
// redirect page if $id is invalid
if ($done) {
header("Location: $ROOT/admin/listnews.php");
exit;
}
?>
if ($_GET && !$_POST) {
...
if (array_key_exists('update', $_POST)) {
Won't that ensure the update code never fires?
If you run that UPDATE from the mysql cli with the same data the user sends does it update?
If not check for escaping characters.
Should $content and $title in the line below be $newstitle and $newscontent?
// prepare the SQL query
$query = "UPDATE news SET title = '$newstitle', content = '$newscontent' WHERE id = $id";
It's a little hard to know exactly what's going on without seeing the HTML source of your form, but I think that the
if (array_key_exists('update', $_POST)) {
block needs to be moved out of the outer if, since it will never be executed if it's there.
If you don't want to use some sort of testing framework, print() is your friend when it comes to debugging your code. Try to find what's executing and what's not; you'll quickly discover which of your assumptions are incorrect, and therefore where the bug is.
Take this if statement out of the nested if:
if (array_key_exists('update', $_POST)) {
...
}
and then add this conditional:
if (count($_POST) && array_key_exists('update', $_POST)) {
...
}
I'm pretty sure that will take care of your problem.
Couple of things to try and narrow down the problem:
echo out some debug text just inside the if (array_key_exists('update', $_POST)) block to make sure you're actually getting in there. The top of your "if" is if($_GET && !$_POST), so you may need to change this $_POST to $_GET
have you tried echoing out $query just before the db call? Does it run on the command line mysql interface ok?
if my reading of your foreach ($_POST as $key => $value) is correct, you'll end up setting variables with the same names as those in $expected - ($newstitle, $newscontent, $id) - but in your sql reference $content and $title. They may be the cause of this bug, but something to keep an eye out for.