I've used several of your guides but I can not get the following to run. If I hardcode the 2 variables in the Select statement it runs fine. I need to use variables, and I can't get the bind statement to work. Plenty of experience with the old Mysql_ but the PDO is still a challenge at this point.
$db_table = "ad";
$ID = "1";
$dsn = "mysql:host=$hostname;dbname=$database;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $opt);
$result = $pdo->prepare("SELECT * FROM :ad WHERE id= :id "); // Line 359
$result->bindParam(':ad', $db_table, PDO::PARAM_STR);
$result->bindParam(':id', $ID, PDO::PARAM_STR);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$product = $row["product"];
$msrp = $row["msrp"];
$sale = $row["sale"];
$content = $row["content"];
echo "<strong>$product</strong> - $content<br />";
// echo $msrp . "<br />";
if($msrp != "0.00") { echo "MSRP $$msrp"; }
if($sale != "0.00") { echo "<img src='/images/c.gif' width='75' height='6' border='0'><span style='color: red;'>Sale $$sale</span>"; }
}
$pdo = null;
The above generates this error,
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '? WHERE id=?' at line 1' in
/XXXXXXXXXXXX/index_desktop_pdo.php:359
Your database structure is wrong. There should be always only one table to hold all the similar data. And therefore no need to make a variable table name.
To distinguish different parts of data just add another field to this table. This is how databases work.
So your code should be
$section = "ad";
$ID = "1";
$result = $pdo->prepare("SELECT * FROM whatever WHERE section=:ad AND id= :id");
$result->bindParam(':ad', $section);
$result->bindParam(':id', $ID);
$result->execute();
Related
I'm working on a login script currently and I'm trying to get comfortable with query's and all those things around it. I'm getting it slightly, but the code below, which checks the username & password when people want to login, doesn't quite work. I get an error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\mystagram\logic\login_validate.php on line 13
<?php
include('../includes/config.php');
include('../includes/database.php');
$username = mysql_escape_string($_POST['username']);
$password = mysql_escape_string($_POST['password']);
$submit = $_POST['submit_login'];
if (isset($submit)) {
$loginquery = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($loginquery) > 0) {
echo 'You are now logged in.';
exit();
} else {
echo 'Wrong username or password.';
}
}
?>
This means that you have an error in your SQL Statement.
Probably you dont have a table named 'users' or the Column 'username' or 'password' is missing.
Change this:
if (mysql_num_rows($loginquery) > 0) {
To:
if (mysql_num_rows($loginquery) == 1) {
And don't save your password in plaintext in the database. And use mysqli :)
you use mysql_escape_string() then '' it was problem. try this code,I hope it will work.
<?php
include('../includes/config.php');
include('../includes/database.php');
$username = mysql_escape_string($_POST['username']);
$password = mysql_escape_string($_POST['password']);
$submit = $_POST['submit_login'];
if (isset($submit)) {
**$loginquery = mysql_query("SELECT * FROM users WHERE username=".$username." AND password=".$password);**
if (mysql_num_rows($loginquery) > 0) {
echo 'You are now logged in.';
exit();
} else {
echo 'Wrong username or password.';
}
}
?>
I am trying to create a magento API to get the pricing of each item. I have a table with all the SKU's i need to get info for. i ran the following for one item and it worked
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$productId = 'ABC';
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
the above code worked fine.
then i tested another code to make sure that my code to query the database and loop through each sku works
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
echo $productId."<br>";
}
The above code works fine. My issue is when i combine the 2 i get a blank screen.
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
}
i get nothing. Any ideas?
update: if $row['sku'] = '9005' will magento think its a product id instead of a SKU?
This line:
$result = $client->call($session, 'catalog_product.info', $arguments);
This can't accept $arguments as the third param. Instead:
$result = $client->call($session, 'catalog_product.info', $row['sku'], null, $att, 'sku');
NB: not sure if 'null' (4th param) is a valid argument for store view. To be safe, replace with the correct store view (default, in most cases).
RTM: http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.info.html
Below is my code:
<?php
$url = $_GET['url'];
$wordlist = array("Www.", "Http://", "Http://www.");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$url = preg_replace($wordlist, '', $url);
?>
<?php
$oDB = new PDO('mysql:dbname=mcnsaoia_onsafe;host=localhost;charset=utf8', 'mcnsaoia_xx', 'PASSWORD');
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja");
$hStmt->execute(array('hjemmside' => $url));
if( $row = $hStmt->fetch() ){
echo "EXIST";
}else{
echo "NOT EXIST";
}
?>
My problem is that it says NOT EXIST, because I know that there is a row which should be found with the following query:
SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja
So why does it say not exist? I have absolutely no idea :(
Instead of
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt=ja");
try
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt='ja'");
The left is most likely a column and the right side is a string? I don't speak your language, but this is the first thing coming to my mind.
You should surround with quotes your not integer variable in your query
AND godkendt='ja'
Or maybe let pdo deal with it
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt = :ja");
$hStmt->execute(array(':hjemmside' => $url, ':ja' => 'ja'));
//^ i added : for placeholder here, you missed it
I would also rather check if rows are returned
if($hStmt->$eowVount() > 0){
$row = $hStmt->fetch()
echo "EXIST";
}else{
echo "NOT EXIST";
}
I have a basic MySQL database table People with 3 columns (ID, Name, Distance)
I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:
$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
However I am just returning a blank array of [].
Update: Changed to mysqli and added dumps:
$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows);
$rows[] = $r;
}
print json_encode($rows);
Returns:
NULL []
Swap your query and connection in the mysql_query-statement:
$sth = mysql_query("SELECT * FROM People", $con);
Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.
Why no mysql_connect ?
var_dump($sth); // check the return of mysql_query()
var_dump($rows); // check the array of mysql_fetch_assoc result
I would check if your query is returning any rows first.
<?php
$rows = array();
array_push($rows, array("name" => "John"));
array_push($rows, array("name" => "Jack"));
array_push($rows, array("name" => "Peter"));
print json_encode($rows);
?>
Produces this output.
[{"name":"John"},{"name":"Jack"},{"name":"Peter"}]
Solved using a combination of answer to get:
$sth = mysqli_query($con,"SELECT * FROM Events");
$datarray = array();
while($row = mysqli_fetch_assoc($sth)) {
$datarray[] = $row;
}
print_r(json_encode($datarray));
i have a php file that works OK.
That php makes recursive search in a local folder, and calculates the last modification DATE of those files.
My question: Every time that i open that php file i want that date to be stored in a SQL table.
-i have created a table with 2 columns (ID, date) where ID=1 then go and update the date field.
but how can i call FROM php file to save the date into sql field?
My php file:
<?php
// LAST FILES UPDATE
function getAllFiles($directory, $recursive = true) {
$result = array();
$handle = opendir($directory);
while ($datei = readdir($handle))
{
if (($datei != '.') && ($datei != '..'))
{
$file = $directory.$datei;
if (is_dir($file)) {
if ($recursive) {
$result = array_merge($result, getAllFiles($file.'/'));
}
} else {
$result[] = $file;
}
}
}
closedir($handle);
return $result;
}
function getHighestFileTimestamp($directory, $recursive = true) {
$allFiles = getAllFiles($directory, $recursive);
$highestKnown = 0;
foreach ($allFiles as $val) {
$currentValue = filemtime($val);
if ($currentValue > $highestKnown) $highestKnown = $currentValue;
}
return $highestKnown;
}
echo '<div align="center" style=" padding-top:5px; margin-top:5px; border-top:dotted #777; border-width:1px;">Last Update Date:<br>';
date_default_timezone_set('Europe/Athens');
setlocale(LC_ALL, array('el_GR.UTF-8','el_GR#euro','el_GR','greek'));
echo strftime('%d %b %Y, %H:%M:%S', getHighestFileTimestamp('../'));
echo '</div>';
$host="localhost"; // Host name
$username="..."; // Mysql username
$password="..."; // Mysql password
$db_name="..."; // Database name
$tbl_name="..."; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET date='HUMMMM HERE HOW TO PULL THE VALUE?' WHERE id='1'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
Try something like this:
// use the function to calculate highest timestamp
$highestdate = getHighestFileTimestamp("../");
// Insert the highest timestamp into the db
$sql= sprintf("UPDATE $tbl_name SET date='%s' WHERE id='1'",
$highestdate);
--EDIT-- merged with Hiroto's answer
You can use these other styles to concatenate string constants with variables
$sql = "UPDATE {$tbl_name} SET date='{$date}' WHERE id='{$id}';";
Or, you could use concatenation.
$sql = "UPDATE " . $tbl_name . " SET date='" . $date . "' WHERE id='1';";
$sql = "UPDATE {$tbl_name} SET date='{$date}' WHERE id='{$id}';";
Or, you could use concatenation.
$sql = "UPDATE " . $tbl_name . " SET date='" . $date . "' WHERE id='1';";