PHP Update class (OO) - php

I have written a PHP OO class which will update 4 fields of a certain row in a table. For now the row is decided by a constant (user with name 'jip')
I have corrected the query in a previous post here, so i'm pretty sure the query itself is fine. So, there must be some sort of error within the class itself. Probaply the vars don't reach the query somehow. I have been looking for hours, but can't find the problem. I have linked both files of the class, since i downt know where the error is, the values just don't show up in the database. If anyone would like to check them, (s)he'd make my entire week! SO here is the link and i hope someone is willing to help :)
UpdateForm.php: http://pastebin.com/dUaZPrn6
Update.class.php: http://pastebin.com/6mnL4DzE

Try replacing mysqli_real_escape_string($conn, $variable) with
$conn->real_escape_string($variable);
For example,
$conn->real_escape_string($this->Lengte_update);
You're using the object-oriented style, so you can't use the procedural escape function. See the docs on mysqli::real_escape_string.
Edit:
The query isn't being executed. You assign the query to $query, but you need to call
$conn->query($query);
For anything to happen in the database.

Related

Multiple MySQL updates from a string using PHP

I need some help putting together this PHP SQL update. I am pretty sure I need a foreach loop to post this query, but I am not sure how to write it.
Basically it needs to match ticketID from the string to ticketID in the database and update that row with the following developer.
The query string will look something like:
ticketID=1483&developer=Reme&ticketID=1484&developer=Reme&ticketID=1485&developer=Reme&isActive=1
Although there could be as many as 30/40 pairs with isActive being a variable to end it all. DBConn and all that is already set up, this is the last thing I need to solve before moving onto sessions.
This is being posted over using an Ajax call. Everything I need is arriving at its destination; it's just getting each pair and update in the database accordingly that I am stumped on.
You can't use the same parameter (ticketID) twice in a query string, because the second will overwrite the first.
In this case you have to use an array:
ticketID[]=1483&developer[]=Reme&ticketID[]=1484&developer[]=Reme&ticketID[]=1485&developer[]=Reme&isActive=1
And then you could use a foreach to loop.
It depends on how you want to update them, but I would suggest using JSON or some other more defined structure.
If you do
ticketID[]=1483&developer[]=Reme&ticketID[]=1484&developer[]=Reme&ticketID[]=1485&developer[]=Reme&isActive=1
you will have one array for ticketID, one array for developer, etc. Which means that you should be really careful with the other on which you are placing the parameters.
Instead of that I would prefer structure like this:
["isActive":1,
"tickets":{"ticketID" :1483
"developer": "Reme"},
{"ticketID": 1484
"developer": "Reme"},
{"ticketID": 1485,
"developer": "Reme"}]
On that you are confident that you are updating the right properties on the right object.

PHP MySQLi possible issue with escaped parameter in escaped statement?

This is something I have been trying to figure out for a bit, it is the most simplest of queries that does not seem to want to work for me (only in php mysqli, works in console sql)
First I am using a prepared statement, merely looking for a match on a specialized id (from another service) to update the relation to use my primary key for easier searching on my end.
The query is as follows:
$query = "SELECT id
FROM {$this->config->dbprefix}{$table}
WHERE sf_id = ?
LIMIT 1";
I use this as one line, I split it up for better readability here
I then check that the prepare statement is valid (I do this in multiple places and it works everywhere else.
if(!($ret = $this->dbo->prepare($query))){
//handle error, this part is never called
}else{
//everything is fine, code in here is below
}
Up to here everything seems fine. Checking table and prefix manually shows they are working and referencing the proper table.
$ret->bind_param('s',$id);
$ret->execute();
$ret->bind_result($retId);
$ret->fetch();
$count = $ret->num_rows;
The problem is here, the query always returns 0 for the num_rows. Checking the query manually and trying it in console returns 1 result as it should. So far with it being such a simple query I just cannot wrap my head around why it would work elsewhere, but not here. I am sure this is the proper way to build it (I have many other queries structured similar).
Is there any kind of confusion I may be experiencing? Something easy to miss that could cause a query like this to not return results?
EDIT:
I have attempted further error handling, and trying an if test on execute does not trigger an error, though I will try more.
To expand I have a raw output of the $query variable and the id variable. By combining them and manually attempting the query in console I get the proper result. My thoughts are on somehow the prepare statement is escaping, causing the string variable $id to not properly match. Though that is just speculation.
You need to call store_result() before trying to access num_rows. Without it, the statement handle does not know how many rows are in the result set.
$ret->bind_param('s',$id);
$ret->execute();
$ret->bind_result($retId);
$ret->store_result();
$count = $ret->num_rows;
// perhaps add error handling based on number of rows here
$ret->fetch();

PHP/MYSQL: What's Wrong With My Query/ PHP variable in query

I've been coding with PHP and MySQL for about a year now and have gotten the hang of it pretty well; constructing really complicated queries with joins and calculated fields and all the other joys of MySQL hasn't been a problem for me in months.
BUT there's something syntactically screwy with the following chunk of code that I can't figure out - even though it's impossibly simple, and, even more infuriating, is closely related to other parts of the project that I'm working on (and which works flawlessly).
Here's the problem code I'm trying to run, followed by the bugchecking I've already done to try to isolate the problem.
If anyone has any suggestions, I'd be totally grateful because I'm beginning to lose my mind.
Problem:
I'm really losing my mind over this, so please don't laugh when you see the code:
$query="SELECT count(somefield) FROM db_name WHERE otherfield='".$myvariable."'";
My query finds no results when using a certain variable as part of a field search - even though I know that there are over 900 records in the database that should match.
Bugchecking:
Because I know the value of the variable I'm passing to the query, I've tried hardcoding it into the query and it works fine.
I've run the query in the MySQL console (again, of course, hardcoded instead of with the variable) and it works fine.
To my mind, these two facts eliminate the possibility that there's something syntactically incorrect with the PHP version of the query.
In order to eliminate all possible database connection issues and to make sure the problem isn't related to iterating through the results returned, instead of trying to get the actual results, I've altered my original query to return only the count of the results and have incorporated the standard or die(mysql_error()) statements during the connection sequence. The query is executing, but is finding 0 results, so that eliminates the possibility that it's a connection issue.
I've verified that the field I'm checking is the correct field for the information I'm looking for (like I said, it runs fine if I hardcode the variable into the query... which, of course, will not be an option in the finished code).
I've checked the type of the variable before trying to pass it into the query (figuring that maybe, because it's pulled from a returned xml earlier in the script, that maybe it was showing up as an array or something). It typed as string.
I've verified that the variable is formatted in the way that I expect it to be found in the database; strtoupper, etc.
I've tried using LIKE '%".$myvariable."'"; still no dice.
Anyone have any suggestions for what I can do to figure out what the hell is going wrong? Thanks so much!
It's not a PHP issue so quotes have nothing to do with it.
The query has no error, so you'll need to debug it step by step.
I. SELECT count(*) FROM table_name
II. SELECT count(*) FROM table_name WHERE field='$myvariable'
Where you're dealing with PHP variables in query, echo the query and run it directly in database to omit PHP's side of error.
III. SELECT count(somefield) FROM table_name WHERE field='$myvariable'
Is the $myVariable escaped? If not, escape it using
$escapedVariable=mysql_real_escape_string($myVariable);
and then run
$query="SELECT count(somefield) FROM db_name WHERE otherfield='$escapedVariable'";
Thanks so much to everyone who tried to help, but I figured it out several hours after posting: The first problem was that I forgot to use mysql_real_escape_string($myvariable)... the reasons for how and why I forgot are manifold, but there it is.
So, after plugging that guy back in (which I had ASSUMED had been in this particular module of my code in the first place, but that's where "assuming" gets you, lol), I thought I had the whole thing licked. Three hours later, and still nothing. THEN I realized that it had to be related to XML that was being parsed into the $myvariable... so around and around we went with that one for a few more hours.
FINALLY, I realized that the real culprit was my eyes (which aren't so great).. what looked like a perfectly legit quoted string while reading a debug echo of the query before running turned out to have leading and trailing white space (which, of course, I instantly removed with $myvariable=trim($myvariable, " "), and, that, of course, solved the entire problem...:<
... Yes, I am an idiot, and I'm sorry, but, after working over this UTTERLY INFURIATINGLY stupid line of code for over 48 hours (I'm used to writing things like:
$query="UPDATE db_one.table_one SET item1='".(string)$result_array[$i][1]."', item2='".(string)$result_array[$i][2]."' WHERE thing3=".(string)$result_array[$i][19];
... and other assorted fun nonsense), I had to resort to asking (because I - no pun intended - couldn't "see" the problem... ugh)... SO... I am an idiot, and I'm sorry (but encouraged by the efforts of all of you nice people who tried to help) and am sorry for wasting everyone's time. I need to learn how to handle XML much *more*.
Sorry and thanks again!
I always wrote it like this
$query="SELECT count(somefield) FROM db_name WHERE otherfield='$myvariable' ";
Try removing the double quotes and dot at the variable name
You shouldn't need the parenthesis around the var. Plus look at other changes.
$query="SELECT count(*) FROM table_name WHERE field='$myvariable'";

When does a MySQL Query actually execute in PHP?

This sounds like a really simple question, but I am new to PHP. If I have a statement like this:
$r =& $db->query("insert into table (col1, col2) values (10, 20)");
Do I have to still execute it, or does it get executed when I reference it? I have another case where I have a select query, which seems logically to run only when I call fetchrow, but the code I am copying from does not call execute or fetch. I would have expected it to, so I cannot tell if it is just that I don't get it, or that the missing execute statement is the problem. It also does not insert the record, but it does not throw an error I can find.
Also, I am a little confused by the =& notation. I looked it up on google, and found a few mentions of it, but I am still not clear on it.
Thanks.
It will be executed when you call query()
The =& notation is obsolete... it used to make the function return a reference to the resource object. But current versions of PHP (>5.0, I think) always pass (and return) objects by reference, so it doesn't really change anything anymore.
The query gets executed when you call the query function. when you talk about code that needs to be fixed, what is broken, and what does the code that "need[s] to be fixed" (according to who?) look like?
& is used in several contexts and it means by reference. You should start reading from here:
http://es.php.net/manual/en/language.operators.assignment.php
http://es.php.net/manual/en/language.references.return.php
In your code snippet it's most likely unnecessary (although you give little clue about what $db is) because the result set is probably an object and objects no longer need to be assigned by reference since that's the default behaviour. If you are learning PHP, be careful with outdated tutorials.
$db->query is a method contained by a class, it's not functional in php out of context. It is possible that this example of yours comes from a larger application that uses a database abstraction layer like ADODB or any of its kind.
If this is the case, then you could refer to the documentation specific to that db abstraction layer, because the query could be contained in a transaction for example and it would not be executed as soon as you call query();
To be sure the query is executed immediately try testing with a simple mysql function:
mysql_query("SHOW TABLES");

call database row in to a function

I am writing a function which is called into a page, but I am not sure how to call information form database into the function in order to use them. Basically I am doing some calculation in the function where I need information form database to do them.
Is there anyone who can give a clue on how ot do this? Many thanks F
From a comment...
What I am trying to do is this: I have
a page in php which retieves some info
from database and all works fine. I am
writing a function that needs to make
some calculation based on some fields
in the database. What I cannot solve
is how to get this information form
the database into my function. I have
tired this: function CalculateCost ()
{ $low_season =
$row_rsbooking['cost']; etc. etc. then
making some calculations but I am
getting nowhere. I am not sure if the
function is getting the information
form database in order to make
calculation.
This is an older question, but as it remains unanswered, I will proffer my two cents.
From your comment to Rafael, it looks like your problem is variable scope. I think you want something like this
function add_one($cost)
{
// just something irrelevant to do
return $cost + 1;
}
// query stuff here, leaving $row with the results
$new_value = add_one($row_rsbooking['cost']);
In other words, pass the column value you need to the function and process the results it returns. If you need to alter your actual row, you could pass the whole row by reference (i.e. add_one(&$row)) and modify it in your function.
Without some more code from you, this is my best guess.
I am not sure I understand the question. But will try to answer it the best way I can.
If you are looking for help on how to connect to a database and execute a query, then have a look at the following link:
http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx
It describes how you can use the SQL Command object to get data from a SQL Server database in the form of a Dataset. Once this is done, you can get a dataset or datatable to get data to any function in your code for calculations.
You could also use an odbccommand. I would post a link, but I don't have enough reputation points to do more than one! :o)
If the Dataset is too big, you could consider using a datable or a SQLDataReader. Again, please have a look at the MSDN for info on those classes.
I hope this helps!
Rafael Jovel
www.augensoftwaregroup.com

Categories