Query fails when I use where - mysql

I have this code
$marker = 'werkz';
$sql = "SELECT name, marker FROM sidebar";
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo'<option>' . $r[name] . '</option>';
}
It works but when I add WHERE marker = $maker; the query fails.
What is the problem?

since you are using PDO, do it like this when passing parameter.
$marker = 'werkz';
$sql = "SELECT name, marker FROM sidebar WHERE marker = ?";
$q = $db->query($sql);
$q->bindParam(1, $maker);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo'<option>' . $r[name] . '</option>';
}

$market is a string. So you should put it between '
something like ... where marker='".$marker."'";

Related

i have issue with my database mySQL select from table

Dears
Please help me in this matter.
I have issue with my MySQL database.
It is working fine if I'm doing inserting records to the table. However, if I'm doing selecting and fetching, the result is 0 despite of the table actually have records.
$sql2 = 'SELECT * FROM `users`';
$result2 = $conn->query($sql2);
echo $result2->num_rows;
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
please help me guys I tried every thing I almost give up.
thanks,
Maybe you can try this code
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=contoh', "root", "root");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql2 = 'SELECT * FROM `user_ranks`';
$result2 = $conn->query($sql2);
while($row = $result2->fetch()) {
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
}
catch (PDOException $e) {
print "connection or query have a problem: " . $e->getMessage() . "<br/>";
die();
}

Troubleshooting mysql Query

I'm having trouble with querying this simple table with a passed in variable:
Here is the relevant code:
// MySQL connection saved to variable $db
// variable $item is passed in as the string "Camera1"
$accessQuery = "SELECT Available FROM inventory WHERE Item = '" . $item . "'";
// This outputs properly as "SELECT Available FROM inventory WHERE Item = 'Camera1'"
echo $accessQuery;
if($oldVal = mysqli_query($db, $accessQuery)){
echo $oldVal // Should be 5 - but there is no output
// echo 'Made it inside if statement' --- This line outputs correctly
}
else{
echo 'Error accessing MySQL query';
}
You need to call a mysqli_fetch_XXX function to get the resulting data from the query.
if($result = mysqli_query($db, $accessQuery)){
$row = mysqli_fetch_assoc($result);
$oldVal = $row['Available'];
echo $oldVal // Should be 5 - but $oldVal causes an error when I try to output
}
else{
echo 'Error accessing MySQL query: ' . mysqli_error($db);
}
$accessQuery = "SELECT Available FROM inventory WHERE Item = '" . $item . "'";
if($res = mysqli_query($db, $accessQuery)){
$row = mysqli_fetch_array($res);
$oldVal = $row['Available'];
echo $oldVal;
}
else{
echo 'Error accessing MySQL query';
}

Changing from Google maps api v2 to v3

I've been using Google geocoding v3 for about 6 months but all of a sudden it's stopped working (I get a 610 error). It's only stopped in the last week or so.
Then I came across this (see the pink box at the top of the page!): https://developers.google.com/maps/documentation/geocoding/v2/
I've read through all the documentation and not sure where to start!
I'm hoping it's a small change as it's taken a long time to get this far, can anyone help?
[See the full site here][1]
UPDATE:
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("teamwork_poh", $con);
$company = get_the_title();
$address = get_field('address_line_1');
$city = get_field('town_/_city');
$post_code = get_field('post_code');
$link = get_permalink();
$type = get_field('kind_of_organisation');
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
$row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
if ($row_dup['cnt'] == 0) {
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '".$type."', '".$link."')");
}
wp_reset_query();
require("database.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "(my key)");
// Opens a connection to a MySQL server
$connection = mysql_connect("localhost", $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
//Initialize delay in geocode speed
$delay=0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/json?address=";
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {
$geocode_pending = true;
while ($geocode_pending){
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "" . urlencode($address) ."&sensor=false";
sleep(0.1);
$json = file_get_contents($request_url);
$json_decoded = json_decode($json);
$status = $json_decoded->status;
if (strcmp($json_decoded->status, "OK") == 0) {
$geocode_pending = false;
$lat = $json_decoded->results[0]->geometry->location->lat;
$lng = $json_decoded->results[0]->geometry->location->lng;
// echo 'here';
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
echo $id;
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
}
else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "\n";
}
// usleep($delay);
}
}
}
As you are storing the coordinates in database it would be best to geocode when you insert new record.
ie
require("dbinfo.php");//Your database parameters
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
//Prepare query
$name = "%".$company."%";//Wildcard for PDO paramerter
$countSql = "SELECT COUNT(*) FROM markers WHERE `name` LIKE ?";
$countStmt = $dbh->prepare($countSql);
// Assign parameter
$countStmt->bindParam(1,$name);
//Execute query
$countStmt->execute();
// check the row count
if ($countStmt->fetchColumn() == 0) { #1 EDIT changed >0 to ==0
echo "No row matched the query."; //EDIT From Row
$q =$address.','.$city.','.$post_code.',UK';
echo "\n";
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
$request_url = $base_url.urlencode($q)."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
if($xml->status=="OK"){#2
// Successful geocode
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$insertSql ="INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES (?,?,?,?,?,?)";
$insertStmt = $dbh->prepare($insertSql);
// Assign parameter
$insertStmt->bindParam(1,$company);
$insertStmt->bindParam(2,$address);
$insertStmt->bindParam(3,$lat);
$insertStmt->bindParam(4,$lng);
$insertStmt->bindParam(5,$type);
$insertStmt->bindParam(6,$link);
//Execute query
$insertStmt->execute();
} #2
else{
"No rows inserted.";
}#2
} #1
else {#1
echo "Rows matched the query."; //EDIT From No row
} #1
}// End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myFile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
I have converted your code to PDO as it is advisable to stop using mysql_functions as these a deprecated.
I have left you to implement how you will deal with geocoding not returning coordinates. You can also check and deal with the following status codes
OVER_QUERY_LIMIT
ZERO_RESULTS
REQUEST_DENIED
INVALID_REQUEST
See pastebin For status code implementation
Going by our earlier comments, there are just a couple of changes required that should get you back on your feet.
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
The next piece about stopping it from going over geocoding limits. What you need to do is set a simple check before you run through the geocoding.
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {// add this line
$geocode_pending = true;
while ($geocode_pending){
//do geocoding stuff
}
}
}// add this close
}

Send an email using php with mysql data included

I'm trying to send a list of recent entries into a mysql table via email once a week using cron jobs. Typically to call the list of recent entries I use this:
$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'")
or die(mysql_error());
while ($list = mysql_fetch_array($result))
But obviously I can't put this code into the $message variable in php mail.
Any ideas?
$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'") or die(mysql_error());
$entries = 'Entries: ';
while ($list = mysql_fetch_array($result)) {
$entries .= $list[entry] . ', ';
}
mail('someone#test.com', 'Stock', $entries);
This is just an example. Not sure what your table looks like.
The mail functions takes a string, and you are returning an array.
So you need to implode it implode(',', $list); or build a string with the result set.
You should use PHPMailer, Zend Mail or Swift_Mailer libraries that are safer and prevent for example from header injection.
try {
$result = mysql_query("SELECT * FROM your_table WHERE blank = 'blank' AND blank2 ='blank2'");
$num_rows = mysql_num_rows($result);
if($num_rows < 1) {
throw new Exception('There is no user who qualifies...');
}
if(!$result) {
throw new Exception('An Error Occurred..');
}
//mail off whatever you need to each user that qualifies based on your query criteria..
while($row = mysql_fetch_array($result)) {
$firstname = stripslashes($row['firstname']);
$lastname = stripslashes($row['lastname']);
$email = stripslashes($row['email']);
//and any other variables you need for the email...
$subject = 'Some Subject';
$message = 'Hello '.$firstname.' blah..blah...';
mail($email, $subject, $message);
//do something else...
echo 'All users emailed.';
}
}
catch (Exception $e) {
echo $e->getMessage();
}

PHP MySQL script gone wrong

I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message
Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
$array = mysql_fetch_array($result);
mysql_close($con);
$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
if($pre == NULL){
$pre = $row["headc"];
$test[0][0]=$row["headc"];
$test[0][1]=$row["subc"];
}
else
{
if($pre ==$row["headc"]){
$sc++;
$test[$hc][$sc] = $row["subc"];
}
else
{
$hc++;
$sc = 1;
$test[$hc][0]=$row["headc"];
$test[$hc][$sc]=$row["subc"];
$pre = $row["headc"];
}
}
}
foreach( $test as $arrays=>$cat)
{
$first = TRUE;
foreach($cat as $element)
{
if($first == TRUE)
{
$htmlString.= '<h3>'.$element.'</h3>
<div>
<ul>
';
$first = FALSE;
}
else
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$element.'</a></li>';
}
}
$htmlString.= '</ul> </div>';
}
return $htmlString;
}
I'm really stuck, the page just keeps timing out the point where i call the function
Try this:
while ($array = mysql_fetch_array($result)) {}
Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]
I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
// arrays can have strings as keys as well as numbers,
// and setting $some_array[] = 'value'; (note the empty brackets [])
// automatically appends 'value' to the end of $some_array,
// so you don't have to keep track of or increment indexes
while ($row = mysql_fetch_assoc($result))
{
$test[$row["headc"]][] = $row["subc"];
}
// don't close the connection until after we're done reading the rows
mysql_close($con);
// $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
// so we step through each headc, and within that loop, step through each headc's array of subc's.
foreach($test as $headc => $subc_array)
{
$htmlString.= '<h3>'.$headc.'</h3><div><ul>';
foreach($subc_array as $subc)
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$subc.'</a></li>';
}
$htmlString.= '</ul></div>';
}
return $htmlString;
}