I am just trying to output the 'cat_find' table to check if my insert statement is correct but mysqli_query is return false. Also if my insert statement is wrong i would like some help with that also:
<?php
$asin = $_POST['asin'];
include("aws_signed_request.php");
echo "You have entered: " . $asin;
$servername = "servername";
$username = "username";
$password = "password";
$database = "database";
$conn = mysqli_connect($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "<br/>";
echo "CONNECTION SUCCESSFUL!";
echo "<br/>";
}
/*$sql = "CREATE TABLE cat_find (
id INT(100) NOT NULL AUTO_INCREMENT PRIMARY KEY,
amazon TEXT(100) NOT NULL,
new_egg TEXT(100) NOT NULL,
ebay TEXT(100) NOT NULL
)";*/
$excel = file_get_contents("skufile.csv");
$explode = explode(',', $excel);
/*for($i = 0; $i<count($explode); $i = $i+3){
//echo $explode[$i];
//echo $explode[$j];
//echo $explode[$k];
$j = $i+1;
$k = $i + 2;
$insert = "INSERT INTO cat_find (amazon, new_egg, ebay) VALUES ('$explode[$i]','$explode[$j]','$explode[$k]')";
}*/
$strSQL = "SELECT * FROM cat_find";
$rs = mysqli_query($conn,$strSQL);
while($row = mysqli_fetch_array($rs)){
echo $row['amazon'] . "<br />";
echo $row['new_egg'] . "<br />";
echo $row['ebay'] . "<br />";
}
// echo $value[0];
$public_key = "PUBLIC-KEY";
$private_key = "PRIVATE-KEY";
$associate_tag = "ASSOC-TAG";
$request = aws_signed_request('com', array('Operation' => 'ItemLookup','ItemId' => $asin, 'ResponseGroup' => 'Large'), $public_key,
$private_key, $associate_tag);
$response = #file_get_contents($request);
if ($response === FALSE) {
echo "Request failed.<br>";
}
else {
// parse XML
echo '<pre>';
$pxml = simplexml_load_string($response);
//var_dump($pxml);
echo $pxml;
echo "<h3>Category/Product Group:</h3> ";
echo $pxml -> Items -> Item -> ItemAttributes -> ProductGroup;
echo "<br/><br/>";
$asin_cat = $pxml -> Items -> Item -> ItemAttributes -> ProductGroup;
}
$sel = "SELECT * FROM cat_find WHERE amazon = '$asin_cat'";
$run = mysqli_query($conn,$sel);
if($run){
echo "Your ASIN has matched an Amazon asin. Here are the Amazon, New Egg and Ebay categories.";
echo "Amazon Category: " . $run[0] . "<br/> <br/>";
echo "New Egg Category: " . $run[1] . "<br/> <br/>";
echo "ebay Category: " . $run[2] . "<br/> <br/>";
}
else{
echo "Your ASIN did not match any ASIN in the Amazon library. try again.";
}
?>
help would be appreciated
Related
So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.
From the code below, i need help on how I can print something like this:
echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
This is the code I need to be modified :
<?php
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
}
echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Just like you normally would print results of SELECT query. Although here it seems there's an ajax call invovled.
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
$result = null;
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
$result = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
$result = $products;
}
// echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
$html = "";
foreach ($result as $row) {
$html .= "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
}
// return as HTML (won't work in ajax)
echo $html;
// or for ajax:
echo json_encode($html, JSON_PRETTY_PRINT) . "\n";
// or
echo json_encode(["html" => $html], JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
I wrote the following code:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
echo $result;
if ($result > 0) {
$result = $result + 1;
$sql2 = "UPDATE Eshop SET quantity = $result WHERE id = $insert";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ($insert, 1)";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
?>
What I want this script to do is select the quantity where the id is $insert and then if quantity > 0, add 1 to the quantity and update the quantity, if not insert the id and quantity = 1 into the table. The table has only two fields id(VARCHAR(32)) and quantity(DECIMAL(8,1)). I tried to do it more general in order to help as many people as possible. Could you please help me? Thanks in advance. NOTE: When I run the script in the browser(after uploading it to the server with the correct username,domain etc.) nothing shows up and I dont even get an error in the console.
You need to extract the result of your query and loop through each row:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$sql2 = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($sql2) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($sql3) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
}
?>
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
//check if particular record exists or not
$count=mysql_num_rows($result);
if($count>0) // if records exists for the particular id
{
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$update = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($update ) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $update . "<br>" . $conn->error;
}
} else {
$insert = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($insert ) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert . "<br>" . $conn->error;
}
} // else qty is <=0
} //end while
}
else {
echo "Records do not exists for that particular id";
}
?>
Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);
When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs
Objective: Take a data entry that contains multiple dates in "$column4" and for each date, create a new entry with $column2, $column3, $column4 and a date followed by one comment.
For this example let's say that:
$column1 is an auto-incrementing primary ID
$column2 = '20141122001';
$column3 = 'something';
$column4 = 'else';
$string = '12/29/2014 2:44PM - working with the lender to remove the mortgage late so we are able to refinance the client. - Person 1 12/04/2014 2:27PM - file suspended until rapid rescore comes back removing late payment from credit. - Person 2';
The example below works for two dates, but how about 1-20 dates? Thanks in advance.
<?php
$host = 'localhost';
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
$db_name = 'intergl8_test';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
echo $string . "<br>";
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches))
{
$date = $matches[2];
}
echo $date;
//////////////////////
if (isset($date)) {
$newstring = str_replace($date,"",$string);
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $newstring, $matches))
{
$date2 = $matches[2];
}
}
echo "<br>";
echo $date2;
////////////////
echo "<br>";
$parts = parse_url($string);
$path_parts= explode($date2, $parts[path]);
$user = $path_parts[1];
$user2 = $path_parts[0];
//$user3 = $path_part[2];
echo $date2 . " " . $user . "<br>";
echo $user2 . "<br>";
$newdate = $date2 . " " . $user;
//echo $user3;
?>
<?php
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
try {
$pdo = new PDO('mysql:host=localhost;dbname=intergl8_test', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $newdate
));
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $user2
));
# Affected Rows?
echo $stmt->rowCount() ." row(s) inserted."; // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
UPDATE:
<?php
$host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
preg_match_all('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "<br>";
/* echo "part 1: " . $val[1] . "<br>";
echo "part 2: " . $val[2] . "<br>";
echo "part 3: " . $val[3] . "<br>";
echo "part 4: " . $val[4] . "<br><br>"; */
// start crazy shit
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host=localhost;dbname='..'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $val[0]
));
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// end crazy shit
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>