Can someone help to figure out why this query will not work on retrieving a certain record from my database?
$db = new mysqli(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$query1 = $db->query("SELECT * FROM `customer` WHERE `wmmw_domain` = '" . array_shift((explode(".",$_SERVER['HTTP_HOST']))) . "'");
while($r = $query1->fetch_array()){
$aff_id = $r['wmmw_id'];
}
echo $aff_id;
This is the link for the test script:
http://evecournoyer.wm-mw.org/testindex.php
If I change one letter, or add a letter, to the database record
(such as evecournoyer1, or vecournoyer), it works.
Is there something in the name, evecournoyer, that prevents the
query from running? It's weird....
Here is one that works:
http://brucetherrien.wm-mw.org/testindex.php
Note: I can retrieve the record using Perl from a command shell, if it matters.
Try using prepare() and binding params and result.
Hopefully something like this:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$stmt = mysqli_prepare($link, 'select name, id from mytable where myfield=?');
mysqli_stmt_bind_param($stmt, 's', $myValue);
$myValue = getSessionHttpHost();
/* bind result variables must match */
$stmt->bind_result($name, $id);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $id);
}
/* close statement and connection */
mysqli_stmt_close($stmt);
......
I would check the data type, encoding and length for the offending field.
I presume you get results for other domains and so your http_host statement is working.
The adding or removing a char from the sub domain makes it work doesn't make sense. If the data type length was being exceeded and the stored value was truncated then I would expect it to fail the select condition but you are adding to it and it works.
I can't see anything in the sub domain that should fail. As suggested above viewing the query string might show up an anomaly in the where condition. Does the query fail if you run it manually through command prompt or client using the result of your http_host code for that domain?
Related
Alright so this bugs the crap out of me, and I can't seem to find anything in the PHP documentation, nor anywhere in the Google resultosphere, so maybe someone can help here.
I'm trying to make a simple request to a database to return a varchar(30).
Code:
$qryID = "select idPhotos from housesphotos where idHouse = ?";
//Prepare the query
$stmt = mysqli_prepare($link, $qryID);
$x = 106;
//Bind the login parameter to the statement
if(mysqli_stmt_bind_param($stmt, "i", $x)){
if(mysqli_stmt_execute($stmt)){
//Bind every column in the select
if(mysqli_stmt_bind_result($stmt, $photoID)){
// $photoID = mysqli_stmt_fetch($stmt);
echo $photoID;
}
}
}
if(empty($photoID)){
printf("EMPTY");
}
As you can guess the output was EMPTY. I have tried using this solution: Strange issue with mysqli_stmt_bind_result but it did not work.
To make sure that everthing was suppost to go correctly I have made the query in the mysql and it worked wonders:
select idPhotos from housesphotos where idHouse = 106
OUTPUT:
591219e92b2fe_591219e92b302
The housephotos is a varchar(30) field. I'm not sure if it's the field type that is messing with the return value. I'm not sure also if it's the connections that I made earlier on the code but I have tried unset($stmt) and other variables to solve the problem but it's not working.
Is this some kind of bug with mysqli_stmt_bind_result() or just a new person's mistake?
You're not actually fetching the results - you commented the mysqli_stmt_fetch() out. The fetch also returns a boolean, not the actual results. Uncomment that line, and remove the variable assignment to it.
$qryID = "select idPhotos from housesphotos where idHouse = ?";
//Prepare the query
$stmt = mysqli_prepare($link, $qryID);
$x = 106;
//Bind the login parameter to the statement
if(mysqli_stmt_bind_param($stmt, "i", $x)){
if(mysqli_stmt_execute($stmt)){
//Bind every column in the select
if(mysqli_stmt_bind_result($stmt, $photoID)){
mysqli_stmt_fetch($stmt); // Remove the comment and variable assignment
echo $photoID;
}
}
}
If you still don't get any results, it might be because the number of rows returned was zero (you can check that with $stmt->num_rows after executing), but since you said the query worked in phpMyAdmin, it's likely that there's some sort of error you're ignoring. To check for errors, add an else to your if conditions, and log $stmt->error inside.
http://php.net/manual/en/mysqli-stmt.fetch.php
It seems that PHP 5.4 (at least the way it's installed on Comcast servers) has a bug that causes bind-result to fail on a varchar field. Changing the field definition to "text" solves the problem.
I've tried to use the solutions presented in this question,
to no avail, so I used this:
$stat = "SELECT MAX(employee_id) FROM employees";
$querysult = intval($connection, $stat);
Where employee_id is an int(3) in the database table.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight. But my question is about what I did immediately after, which was
echo "Id: " . $querysult;
and which output nothing but
Id:
and no number. I've also tried casting the number to a string, and concatenating it to an empty string before the echo statement.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight
This of course is quite impossible, unless you are getting something from a previously executed query that uses the same variable names.
I think your main problem is that accessing the value of the query coded using just SELECT MAX(employee_id) will return a column with the name MAX(employee_id) and that is not a valid PHP variable name. So what you have to do is give that column another name that is a valid PHP variables name using this syntax SELECT MAX(employee_id) as max_empid which renames the column to max_empid
I am assuming nothing so I will also include a connection to the database in my answer. You will need to replace the my_user, my_password and my_db values, or ignore the connection if you have already dont that somewhere else. I have also used the Object Oriented approach to MYSQLI, if you are using the proceedural calls, you may have to amend the code accordingly
// connect to your database
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
// build query and use an alias for the `MAX(employee_id)`
// so you can easily use its name in the result set
$sql = "SELECT MAX(employee_id) as max_empid FROM employees";
// Now we must execute this query
$result = $mysqli->query($sql);
// Now we must chech that the query worked
if ( $result === FALSE ) {
echo sprintf( 'Query Failed: %s<br>%s', $sql, $mysqli->error);
exit;
}
// now we must read one of the rows from the result set
// produced by the ->query() command.
// In this case there of course there is only one result row
$row = $result->fetch_object();
echo 'Id: ' . $row->max_empid;
It may be because you are trying to convert a connection to an int value.
Try this
$connection = new mysqli();
$querysult =mysqli_query( $stat);
printf("Select returned %d.\n", $querysult->num_rows);
So, first off, I know there are certain rules you have to follow when preparing a LIKE statement with PDO. I have already looked these up and I'm trying my best to follow them, but the query consistently returns no results even though I know the query itself is legitimate (MySQL command line client works correctly with the query).
This is for a school project; I need to make a website with a MySQL/php backend for a fictional bookstore.
I have a class in a php script called DBConnection. It is in a separate namespace (hence the backslashes for PDO objects and functions). This is part of it:
<?php
class DBConnection {
// ...
public function prepAndExecute($sql, $args) {
try {
$stmt = $this->conn->prepare($sql);
for($i = 1; $i <= count($args); $i++) {
$stmt->bindValue($i, $args[$i-1], \PDO::PARAM_STR);
}
$stmt->execute();
return $stmt;
} catch(\PDOException $e) {
return false;
}
}
}
?>
The actual MySQL query I am trying to run:
SELECT ISBN, Title, Author, Price FROM Book WHERE Title LIKE "%rich%";
My attempt at using a PDO Prepared Statement to run this on the website:
<?php
// based on the search form from the previous page
// (all values are set correctly by the form, already tested)
$criteria = $_POST["searchCriteria"]; // "Title" (from a <select> element)
$term = $_POST["searchTerm"]; // "rich" (from the text box)
$conn = new DBConnection(); // uses namespace correctly, just didn't
// include here for simplicity
$sql = "SELECT ISBN, Title, Author, Price FROM Book WHERE ? LIKE ?";
$stmt = $conn->prepAndExecute($sql, array($criteria, "%" . $term . "%"));
// I have also tried $term = "%" . $term . "%", still no luck
echo $stmt->rowCount(); // 0
?>
I ran the above query in the MySQL command line, and got 1 result as expected. I know the class/functions work because I use that same function to run all other SELECT and INSERT queries, and have had no problems until I try to run this LIKE statement.
Am I doing something wrong? Because I double and triple checked everything and could have sworn I was doing this right.
http://php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);
I created this code:
$statement = $db->prepare("SELECT * FROM phptech_contact");
$statement->execute();
$result = $statement->result_metadata();
$object = $result->fetch_object();
print_r( $object );
When I run it, it doesn't work. Can anybody tell me why it doesn't work?
I have 20 rows in this table so data should be returned.
From http://ch.php.net/manual/en/mysqli-stmt.result-metadata.php
Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().
As long as you don't need this meta data you don't need to call this method.
$statement = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$statement->execute();
$stmt->bind_result($fld1, $fld2);
while ($stmt->fetch()) {
echo "$fld1 and $fld2<br />";
}
But I really dislike the mysqli extension. PDO is much cooler ... ;-)
$db = new PDO('...');
$stmt = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$stmt->execute();
while ($obj = $stmt->fetchObject()) {
// ...
}
or
$objs = stmt->fetchAll(PDO::FETCH_OBJ);
if you're trying to get the rows from the database, the function you need is mysqli_stmt::fetch(), not mysqli_stmt::fetch_metadata()
You're also missing a few steps. When using prepared statements, you must specify the fields you would like to return instead of using the star wildcard, and then use mysqli_stmt::bind_result() to specify which variables the database fields should be placed in.
If you're more familiar with the original MySQL extension, prepared statements have a different process to use. If your select statement has a parameter (eg., "WHERE value=?") prepared statements are definitely recommended, but for your simple query, mysqli:query() would be sufficient, and not very different from the process of mysql_query()
I believe the problem is that mysqli_stmt::result_metadata() returns a mysqli_result object without any of the actual results — it only holds metadata.
So what you want to do is use $result = $statement->bind_result(...) and then call $result->fetch() repeatedly to get the results.
One of the comments under the bind-result() article shows how to do this for a query like yours, where you don't necessarily know all of the columns being returned.
I know this particular query works, as I tested it with unprepared, procedural methods. Here it is:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($content);
$stmt->fetch();
echo $content;
$stmt->close();
I realized that, since I have an id column as an index in the sections table, I needed to bind that as a result as well, given the above statement at php.net, (thanks again, Bill).
Here's the new code:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($id, $name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
Thanks again to all who can offer suggestions. (I'm curious: I find it hard to debug when using the OOP style of prepared statements in this way. Is there, for example, an easy way to simply see the query that was actually used?)
If I do the following, just as a quick-and-dirty example:
$name = 'introduction';
#mysql_connect('host', 'user', 'pass');
#mysql_select_db('db');
$query = "SELECT name,content FROM sections WHERE name = '$name'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_object($result)) {
$content = $row->content;
echo $content;
}
My data appears and all is well. If, however, I do the following:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
Which I believe is correct (feel free to yell if not, of course), I get nothing. What's more, with that code, when I do an html validation (just in case), I get an internal server warning (500), which I take to be a problem with the sql code. Am I just nuts?
I don't see anything wrong with your preparation of the statement or use of parameters, but there is something wrong in your binding results:
http://php.net/manual/en/mysqli-stmt.bind-result.php says:
Note that all columns must be bound
after mysqli_stmt_execute() and prior
to calling mysqli_stmt_fetch().
(emphasis mine)
The above doc should be taken as all columns in your query, not all columns in your table.
Okay, I just tried this myself. If I omit the $name column, it gives this warning:
PHP Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in mysqli.php on line 9
PHP Stack trace:
PHP 1. {main}() /Users/bill/workspace/PHP/mysqli.php:0
PHP 2. mysqli_stmt->bind_result() /Users/bill/workspace/PHP/mysqli.php:9
But it does fetch the data.
If I bind both $name and $content to the results of the query, it works without error or warning.
So I'm forced to ask you: are you sure there's a row in the database that matches your condition? That is, where name = 'introduction'? Keep in mind that in SQL, string comparisons are case-sensitive by default.
One mistake I see people make frequently is that they connect to a different database in their PHP script than the database they use for ad hoc queries. So you need to be absolutely sure you're verifying that the data exists in the right database.
Shouldn't that be
$stmt->bind_result($name, $content);
As you select 2 columns