Multiple Cells Not Updating into Mysql - php

Fairly new to php, please forgive me if my code is not eloquent.
I have a table/form with multiple rows/cells. Each cell is a drop down box. I've built this to UPDATE existing mysql-rows.
I'm having trouble figuring out how to press the submit button on the form and UPDATE all the mysql-rows. I've successfully updated mysql fields individually, but this is my first time trying to update multiple sql-rows at the same time.
In my front-end (let me know if you need me to post it), I run the below code to create a new increment variable for each -input type="submit" name="blah"...-
$namefieldname = 'name'.$i;
$positionfieldname = 'position'.$i;
$hoursdropdown = 'hours'.$i;
$overtimedropdown = 'overtime'.$i;
So name="blah" I write as name="'.$namefieldname.'" for example. I have a different form that uses this same $i concept to INSERT information and it works fine.
Below is the code that I'm not getting to work. This is what the -form action- goes to. The page processes without errors - but doesn't update mysql. I've double checked all names and everything is spelled correctly.
For now I've cut down the columns to try to get just this one column to update mysql.
<?php
include_once('toolbox.php');
//mysql connect info
$projectid = $_POST['projectid'];
$transcriberid = $_POST['transcriberid'];
for($i=0; $i<$staffcount; $i++) {
$positionfieldname = 'position'.$i;
//is a drop down of 5 choices
$thisposition = $_POST[$positionfieldname];
mysql_query("UPDATE transcribers SET transcriber_position='$thisposition' WHERE transcriber_id= '$transcriberid'");
}
header('Location: ./);
?>

First, you shouldn't use the mysql extension in new programs any more, because it is deprecated since version 5.5, and it was removed in PHP 7.0.0. Instead, use MySQLi or PDO_MySQL extension.
Second, it is important to handle user given data (e.g. from $_POST) appropriately before using them to concatenate sql statements. If the user gives a quote sign, he/she could alter your statement such as terminating it and update some other data in some other tables. If you use PDO_MySQL, function PDO::quote() can help you to prevent this:
$thisposition = $mysql_connection->quote($_POST[$positionfieldname]);
Even better is to use a prepared statement. It contains only placeholders where user provided data is used and the actual data is bound to this placeholders.
$stmt = $mysql_connection->prepare("UPDATE transcribers SET transcriber_position=:value");
$stmt->bindValue(':value', $transcriber_position, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
For updating multiple columns in a table, you can just list them, separated with comma, here an example:
mysql_query("UPDATE transcribers SET transcriber_position='$thisposition', transcriber_value=5 WHERE transcriber_id= '$transcriberid'");

Related

Syntax for UPDATE of a record in MYSQL

Is the following update query a legal statement? It replaces the existing value with an empty value instead of the word gossamer. It does not fail as far as I can tell. It changes the value in the database from whatever it was before to empty.
$sqld = "UPDATE mynotes SET notes = 'GOSSAMER' WHERE id = '2039'";
$resupdate = mysql_query($sqld) or die(mysql_error());
if ($resupdate) {
$success=1;
$message .="success with update";
}
The query is part of an an API and it returns a result in JSON. While this makes debugging more time consuming, this should be besides the point. If the above is an entirely legal update statement, then at least I can rule out a syntax issue and search for the problem elsewhere.
I have verified that the above code does work in a standalone php file. Something else in code is causing the issue.
Yes, mysql is deprecated in favor of mysqli and PDO. But upgrading legacy site is not in job scope.
It replaces the existing value with an empty value instead of the word gossamer
Assuming this statement is accurate then either:
1) the attribute 'notes' is of type ENUM whose values do not include 'Gossamer'. But you didn't share the DDL for the table.
2) Your code is not executing the query you've shown us here - the query it is executing should be in your MySQL logs

Why is my data not stripping properly with mysql_real_escape_string?

Here is my code below:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
//Finally, we can actually the field with the student's information
$sql = <<<SQL
UPDATE `database` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '{$studentTalking}',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
I am trying to use the mysql_real_escape_string to allow apostrophes entered into our form by the user to go to the database without breaking the database, however the data will either go through as null or the apostrophe will break the database. I have changed everything I could think of, and can't figure out why this isn't working. Yes I understand the that injections could break our database, and we will work on updating the code soon to mysqli but we need this working now. I suspect my syntax isn't correct and the first line may need to be moved somewhere, but I am not the strongest in PHP and I am working with code that was written by previous interns. Thank you in advance.
Switch to mysqli_* functions is the right answer.
The answer if intend to stayg with the deprecated and dangerous mysql_* functions:
Here you set a new variable equal to your escaped $_POST[]:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
But in your SQL you still refer to the $_POST array... Switch your SQL over to use your new variable you created
$sql = <<<SQL
UPDATE `tgtw_rsvp` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '$studentTalking',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
Because you are not using the stripped variable but still the raw POST data.

How to share connection_id between 2 queries?

I need to execute two SQL statements together because connection_id() in the first statement will be used in the Mysql view wp_statistics_benchmarks.
Without the connection_id(), the wp_statistics_benchmarks is an empty view. The following SQL works fine and get results:
replace into wp_params (`view_name` , `param1_val`, `connection_id`)
values ('benchmarks', 484 , connection_id())
;
select * from wp_statistic_benchmarks;
But, to work with wordpress, the following code doesn't work:
$mysqli = new mysqli(.....);
$results = $this->_wpdb->query("
replace into wp_params (`view_name`, `param1_val`, `connection_id`)
values ('benchmarks', $connected_from, $mysqli->thread_id);
select * FROM `wp_statistic_benchmarks`;"
);
How can I convert these two mysql codes into Wordpress wpdb queries?
Use the wpdb object twice.
$this->_wpdb->query('replace into ...');
$rows = $this->_wpdb->get_results('select ...')
Let me put it another way, select * from wp_stat ... and replace into wp_params ... from your original "mysql codes" are separate statements without any relation to each other.
You think that you need to run them in sequence, whereas in fact you can have a cup of coffee or even travel around the earth in between those replace into and select statements and they would still do the same thing. If that is not the case, then your question lacks information necessary to provide a good answer because wp_params is not a standard table in wordpress and neither is the view. I don't think you understand your problem.
Besides, running them as I suggest is equivalent with your "mysql codes". Moreover, $wpdb->query returns the number of affected rows or false, so you will never be able to run a select statement with $wpdb->query() to retrieve a set of tuples.
How can I convert these two mysql codes into Wordpress wpdb queries?
You can't. That's because you're using wpdb and it only supports one query per ->query() call. However, if you're using Mysqli with wpdb, you can use the multi_query() method of it with wpdb. Here is how:
To use multiple queries, you need to ensure that wpdb uses Mysqli (e.g. define the USE_EXT_MYSQL constant as FALSE in your Wordpress config).
Then you can obtain the mysqli instance from the wpdb object, either with reflection or a helper class/module:
abstract class wpdb_dbh extends wpdb
{
static function from(wpdb $wpdb) {
return $wpdb->dbh;
}
}
Mysqli is then available without creating a new instance:
$mysqli = wpdb_dbh::from($this->_wpdb);
As this is a valid Mysqli instance you can run multi query.
But just obtaining the same Mysqli instance as wpdb uses it probably the most important thing here as otherwise your open an additional connection with new mysqli(...) which you need to prevent.
Additionally take care that $mysqli->thread_id is a fitting replacement to connection_id() following the same formatting/encoding. You should be able to use connection_id() directly anyway, so I actually see not much reason to access the thread_id member, but it's perhaps only because you tried some alternatives and I'm just over-cautious.
The ';' query delimiter is purely an SQL shell convenience and is not a part of the MySQL dialect so you're correct that your code doesn't work.
Here's the actual replacement code:
$mysqli = new mysqli(.....);
$this->_wpdb->query(
"replace into wp_params
(`view_name`, `param1_val`, `connection_id`)
values ('benchmarks', $connected_from, $mysqli->thread_id)");
$results = $this->_wpdb->query("select * FROM `wp_statistic_benchmarks`");
This is the same as Ярослав's answer above.
Update:
If your code is still not working you might have to enable persistent connections in Wordpress.
Update 2:
There was a missing space between in the second query's select statement and the * shorthand all columns selector. Interestingly this may or may not cause an issue for you, it doesn't seem to bother my MySQL 5.5 command line shell.
If I understand your requirements (and I do not know wordpress), you are inserting a row to wp_params with a column called connection_id. I would assume that this value will be unique on the table. I would be tempted to add an integer autoincrement id field to the table and then get the value of that (last insert id). Then use this id in a WHERE clause when selecting from the view.

Insert mysql error when parsing a webpage

Hi when ever I want to insert a comment into my database, I sanitize the data by using Mysql Escape String function this however inserts the following verbatim in field. I print the comment and it works fine and show me the text however when ever I sanitize it, it literally inserts the following into my db
mysql_real_escape_string(Comment)
This is my insert statement, The Id inserts correctly however the comment doesn't it just inserts the "mysql_real_escape_string(Comment)" into the field. what can be wrong?
foreach($html->find("div[class=comment]") as $content){
$comment = $content->plaintext;
$username = mysql_real_escape_string($comment);
$querytwo = "insert into Tchild(Tid,Tcomment)values('$id','$username')";
$resulttwo = $db -> Execute($querytwo);
}
If I'm reading the documentation correctly, you should make the call like this:
$db->Execute("insert into Tchild(Tid,Tcomment)values(?, ?)", array($id, $username));
That will account for proper escaping. Having unescaped values in your query string is dangerous and should be avoided whenever possible. As your database layer has support for SQL placeholders like ? you should make full use of those any time you're placing data in your query.
A call to mysql_real_escape_string will not work unless you're using mysql_query. It needs a connection to a MySQL database to function properly.
Since you're using ADODB, what you want is probably $db->qstr(). For example:
$username = $db->qstr($comment, get_magic_quotes_gpc());
See this page for more information: http://phplens.com/lens/adodb/docs-adodb.htm

UPDATE only provided fields in MySQL table using PHP

I have a user table with and id field and 10 other fields storing user details of various types that the user can change via various web forms. I want to have a PHP script that gets POSTed changed values for some subset of these fields, and UPDATEs only those fields that are received in the POST data. I'm finding this surprisingly difficult to do in a way that doesn't suck. We use mysqli for all database interaction in the rest of this application so mysqli-based solutions are strongly preferred.
The options I've considered and dismissed so far:
1) Run a separate UPDATE query for every field provided in the POST data - yuck, I don't want to hit the database up to 10 times for something that could be done in one query.
2) Have a dictionary mapping field names to the fields' data types, and iteratively construct the query by looping through the provided fields, checking whether they are text fields or not, calling mysqli_real_escape_string on the string fields and otherwise sanitizing the others (e.g. by type checking or sprintf with '%i' placeholders). - Yuck! I could probably safely do things this way if I was careful, but I don't want to make a habit of using this kind of approach because if I'm careless I'll leave myself open to SQL injection. Parameterized queries don't give me the potential to screw up dangerously, but this approach does. My ideal is to never concatenate any data into an SQL query manually and always rely upon parameterized queries; the database libraries of other languages, like Python, let me easily do this.
3) Use a parameterized query - this is my ideal for everything, since as long as I insert all externally-provided data into my query via the bind_param method of a mysqli statement object, I'm immune to SQL injection and don't have to worry about sanitization, but using parameterized queries seems to be impossible here. The trouble is that bind_param requires that the data be passed as variables, since all arguments after the first are passed by reference. I can reasonably elegantly iteratively construct a query with ? placeholders, and while I'm at it construct the string of types that gets passed as the first argument to bind_param ('ssiddsi' etc.), but then there's no way I can see to choose at runtime which of my 10 fields I pass to bind_params (unless I have a switch statement with 10^2 cases).
Is there some PHP language construct I'm missing (something similar to array unpacking) that will allow me to choose at runtime which variables to pass as arguments to bind_param? Or is there some other approach I haven't considered that will let me solve this simple problem cleanly and safely?
You can easily combine 2 and 3 by means of my SafeMySQL library.
The code will look like
$allowed = array('title','url','body','rating','term','type');
$data = $db->filterArray($_POST,$allowed);
$sql = "UPDATE table SET ?u WHERE id=?i";
$db->query($sql, $data, $_POST['id']);
note that $allowed array doesn't make all these fields necessarily updated - it just filters POST fields out. So, even $_POST with only id and url would be correctly updated.
Nevertheless, using prepared statements, although toilsome, also quite possible.
See the code below
public function update($data, $table, $where) {
$data_str = '' ;
foreach ($data as $column => $value) {
//append comma each time after first item
if (!empty($data_str)) $data_str .= ', ' ;
$data_str .= "$column = $value" ;
}
$sql = "UPDATE $table SET $data_str WHERE $where";
mysqli_query($sql) or die(mysqli_error());
return true;
}
$data is an array, in your case it's $_POST.
If you want to be more specific about the data to be saved from $_POST array, you can define an array of allowed columns. For example,
$allowed = array('id', 'username', 'email', 'password');
By doing this, you can filter your $_POST array and pass it to update() function.

Categories