In my php.Mysql ($sql) result should be 1.Sysum should not be empty in another word, mysql_num_rows($sel) > 0 should be true.
But actually,mycode can not work.I don't know why.Who can help me?
$conn = new PDO('mysql:host=localhost;port=3306;dbname=hpc' , 'root' , 'Yd');
$Name=$_COOKIE['PName'];
$sql = "select sysnum from hpc where handler='".$Name."' and stat='N';";
$sel=$conn->query($sql);
if(mysql_num_rows($sel) > 0)
{
mycode;
}
Oh boy that went quite fast with your comment, even before mine :P
So, the answer is simple: You can't use mysql_num_rows on a PDO connection. That are two different drivers. Thats like you try to start the car of your wife with your own keys. Principally, both are keys, but they don't work with any car.
Its the same here in your case. mysql_num_rows comes from the OUTDATED mysql driver. (Don't use mysql_* at all, its not longer supported in PHP7 and deprecated). To do it with PDO is the right way, but you have to adapt your code a bit.
$Name=$_COOKIE['PName'];
$sql = "select count(sysnum) from hpc where handler='".$Name."' and stat='N';";
$sel=$conn->query($sql);
$rows = $sel->rowCount();
echo $rows;
Hope that work, if not, let me know. I know I had some troubles the last time I tried to do a rowCount with PDO.
IMPORTANT - DANGER:
Also I really recommend you to take a look at http://bobby-tables.com and learn something about SQL injection. Your code actually is not save at all and your database can be hacked quite easy. Since you're using PDO, nothing stops you from using prepared statements, what would make your code much better.
Hope I could help you. If you have any other questions or something shouldn't work, please let me know.
fetch result into an array and count items using count function, like this:
$Name=$_COOKIE['PName'];
$sql = "select sysnum from hpc where handler='".$Name."' and stat='N';";
$sel = $conn->query($sql)->fetchall();
if(count($sel) > 0){
mycode;
}
Related
On first inspection of the differences in application of the mysql*() and mysqli*() families of functions, it appears to me that
$seta = mysql_query("SELECT * FROM table WHERE field = $Filter", $database);
Can be rapidly replaced with:
$seta = mysqli_query($database, "SELECT * FROM table WHERE field = $Filter");
Similarly, it also appears that
IF ($A = mysql_fetch_array($seta)) {
do {
//code here
} while ($A = mysql_fetch_array($seta));
}
Could be replaced with:
IF ($A = mysqli_fetch_array($seta)) {
do {
//code here
} while ($A = mysqli_fetch_array($seta));
}
Will this work the way I am expecting it to? As it worked before mysqli*()?
PLEASE NOTE: I am not asking if I SHOULD do this, only if I CAN do this. I know full well that slapping a band-aid on a broken leg is useless... That said, I don't have that many hours of coding/testing time before the Demo in March this is being prepped for.
Yes, I understand the this is vulnerable code. I won't go to production without safeguards. I also realize that I am not using all the power of the mysqli*() family of functions this way.
My goal is to refactor everything properly when there isn't such a heavy time crunch (Yes, I know, famous last programmer words). I just need the patched code to run for a Demo then I can retire it.
I have high hopes that with a working prototype -- both in situ and on a server I'm spinning up just to demonstrate the need for software updates -- I'll be able to leave the PHP v4.x blues behind.
Project:
PHP/MySQL better user searching
Also checked:
How to upgrade from mysql* to mysqli*?
PHP Migrating from mysql* to mysqli
Above titles were trimed of underscores to prevent formatting
The quick and dirty method, with emphasis on dirty, is to do it this way by converting mysql_query to mysqli_query and so on. The problem is mysql_query is really clunky to use so preserving that coding style is not going to help clean anything up.
Although I'd strongly recommend switching to PDO, it's a more flexible and capable database layer, if you want mysqli then what you want to do is employ parameterized queries and bind_param to add user data to your query. This solves the vast majority of SQL injection bugs out of the gate. I'd also suggest using the object-oriented interface so your updated code is obvious. The difference of a single i can be easy to overlook, plus it's typically less verbose.
In other words, your replaced code looks like:
$stmt = $database->prepare("SELECT * FROM table WHERE field=?");
$stmt->bind_param('s', $filter);
$res = $stmt->execute();
If you're disciplined about doing this you should catch all your SQL mistakes.
PDO is nicer because of named parameters:
$stmt = $database->prepare("SELECT * FROM table WHERE field=:filter");
$res = $stmt->execute(array('filter' => $filter));
That usually means less code in the long-run.
I'm updating a site from MySQL to MySQLi, using OOP.
For the most part things are going well, but this line is giving me divine trouble:
$pager_total = mysql_num_rows(mysql_query($MySQLctr,$MyDB));
I've tried
$pager_total = $MyDB->query($MySQLctr)->num_rows;
and
$pager_total = ($MyDB->query($MySQLctr))->num_rows;
and
$new_object = $MyDB->query($MySQLctr);
$pager_total = $new_object->num_rows;
but no avail.
Any thoughts?
OOP mysqli is very simple :) try this example
$DBH=new mysql('location of database','username','password','database');
$get=$DBH->prepare('SELECT COUNT(*) FROM table');//notice the count(*) in the query, it's not the same as mysql_num_row() but works in the same way
//prepare is also a more secure way of processing query, please look up the difference between prepare and query though.
//$DBH->prepare('SELECT * FROM table WHERE ID=2'); will not work.
$get->execute();//execute the above prepared statement
$get->bind_result($count);//get the result of the query, should be whatever COUNT(*) returns
$get->close();//don't forget to close your connection
The mysqli of mysql_num_row() is $query->num_rows().
I added a little bit extra to get you started with OOP mysqli :)
Notice though that I didn't use $get->num_rows() but COUNT(*) instead for a more simple example. Here is another method you may be more familiar with:
$counter=$DBH->query('SELECT * FROM table');
echo$counter->num_rows();
Also see here for more examples.
Thank you for your help everyone. It turns out that the db connection was being closed prematurely by one of the included files. I've noticed, during this project where I'm transitioning the code from procedural MySql to OOP MySQLi that the db closures didn't affect the functionality of the site before, but definitely do once OOP MySqli is in place. I'm curious why.
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}
This is something I used to do in Java, I was wondering if there is an equivelant in PHP.
In Java, I'd do something like this (pseudo only as I've gotten rusty in the last year or so):
preparedStatement = new StringBuilder("SELECT something FROM somewhere");
ResultSet rs = preparedStatement.executeQuery();
while(rs.next())
{
if (someTest)
{
rs.updateRow[1]="someNewValue";
}
}
This is wide of the mark syntactically (and I bet it won't compile) but I hope it explains the kind of thing I was able to do. Not sure if it saved an actual DB query from being run but it did make my code alot cleaner.
So in PHP, I have something like this:
$query = "SELECT something FROM somewhere";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result))
{
if (someTest)
{
//how can I update this row without coding another query?
}
}
Is there an equivelant to this in PHP?
I'm using the vanilla mysql db methods, not mysqli or that other one (pod or something?) but I think I'd be safe to use mysqli on our servers if I need to.
Any help appreciated
Nope, you could however use mysql_fetch_object with a custom classname, and define a save() method on it that will run the update query for you. Keeps the logic out of the loop and in a Model for that data. Or use an full-blown ORM library which does this kind of thing.
As far as I'm aware, you can't update the row without running another query such as:
UPDATE table SET column1="value" WHERE (column2="value");
i am used to writing regular pdo statements into php how can i continue doing that without having to learn active records or use whatever else method there is in CI
i did something like this
$sql = "select column1,column2 from table where column_id = :column_id and column_2 = :something"
$query = $db->query($sql);
$query->bindParam(":column_id", $_GET['value'], PDO::PARAM_INT);
$query->bindParam(":something", $_GET['something'], PDO::PARAM_STR);
$query->execute();
while($row = $query->fetch(PDO::FETCH_OBJ)
{
print $row->data;
}
rather than using $_GET i can probably use $this->uri->segment()
which hopefully works with this...
I looked at active record and that looks like a huge bad idea, i dont know what Ellislab was thinking. no clue how complex queries can go into them. I am a newb learning from nettuts i can be wrong and please show me if i am. just speaking from what i have learned so far.
writing query statments the otherway such as
$query = $this->db->query("my sql statement") i would have to escape each value i am querying with codeigniters escape methods or just use mysql_real_escape_string. which is something i could of done to begin with before diving into the mvc world but i chose pdo because its something that already works well.
how can i implement what i am already used to?? I dont mind modifying core files , ill hopefully end up learning all the classes to reverse engineer it but until that day comes i'll have hopefully written my own mvc.
thanks
Sorry, I fail to see how this:
$query = $this->db->select('column1,column2')
->from('table')
->where('column_id',$this->input->get('value'))
->where('column_2',$this->input->get('something'))
->get();
return $query->results();
"looks like alot of extra work" rather than this:
$sql = "select column1,column2 from table where column_id = :column_id and column_2 = :something"
$query = $db->query($sql);
$query->bindParam(":column_id", $_GET['value'], PDO::PARAM_INT);
$query->bindParam(":something", $_GET['something'], PDO::PARAM_STR);
$query->execute();
Keep in mind that AR automatically escapes, so you don't worry about SQL injections.
If you're more used to query bindings, you can also do
$sql = "select column1,column2 from table where column_id = ? and column_2 = ?";
$query = $this->db->query($sql, array($this->uri->segment(3), $something);
and take advantage of parametrization, without using Active Record class.
Nothing prevents you from using PDO, or even mysql_* for what that matters, instead of Active Record class. And your query has nothing that prevents CI from using it - apart from the $_GET array which you must enable, but can easily subsitute with $this->input->get() or fetch manually the URI segment or have it passed automatically to the controller's method, as usually happens.
You say "am a newb learning from nettuts" , but still say that Ellislabs doesn't know what it's doing; altough lightweight and far from perfect CI has a solid community, is actively developed and its general consensus is quite high; and if it decides to have the Active Record the way it is, there's a reason.
Also, consider that other more proper and real ORMs, like Propel or Doctrine, use a similar style in running queries (and you can use them too, instead of AR if you like it), taking advantage of PHP5 concatenation. An example taken right from the frontpage of propel:
$books = BookQuery::create() // retrieve all books...
->filterByPublishYear(2009) // ... published in 2009
->orderByTitle() // ... ordered by title
->joinWith('Book.Author') // ... with their author
->find();
So I see nothing strange in the way CI's Active Record is implemented or structured. If your code is not running, please give more details, like error codes and so on, so we can actually understand why it's not working.
IMPORTANT:
I just read the changelog from the latest version; try downloading it (version 2.10), as they state:
Added a PDO driver to the Database driver.
You're not gaining anything by using CI's DB class if you're not using ActiveRecord or the other functions. Why not just use PDO natively?
By the way, you could do the exact same thing this way:
$result = $this->db->
select(array('column1', 'column2'))->
where(array(
'column1' => $this->input->get('value'),
'column2' => $this->input->get('something')
))->get('table')->result();
print_r($result);