This part is for gathering my data through an API.
foreach($result['List'] as $feedback)
{
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
}
This part is the code that I used to insert into my results directly after retrieving them.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
mysql_select_db('dctdb3');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Only one data is being inserted into the database and it is the last data displayed.
I was wondering how I can change my code so that I can insert all the data at the same time and not repetitive?
Thank you for your help.
Put the insertion inside the loop. Otherwise, the variables just have the last values that were set in the last iteration of the loop.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dctdb3');
foreach($result['List'] as $feedback) {
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
echo "Entered data successfully<br>";
mysql_close($conn);
Make sure your second block of code is inside your first block of code (place your second block above the right-curly-brace). Then it will occur for each iteration of the foreach loop (each result) and insert a record for each one.
You cannot insert array into database hence place the query inside a loop. This thread may help you alot.
Related
I am creating PHP stmt similar products display script this script working but not showing similar products I want to display similar products title
Here is my code
<?php
$id=$row['id'];
if($stmt = $con->prepare("SELECT title
FROM products order by rand() limit 3
")){
$stmt->execute();
}
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
//results
}}
?>
view.php
<?php
if(isset($_GET['id'])) {
include("config.php");
$id = $_GET['id'];
$sql = "select * from products where id = '$id'";
$result = $con->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
//results
}}}
?>
Ensure that Database credentials were okay.
Try the code below and let me know
1) Query using rand() method( This is what you want)
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'your password goes here';
$dbname = 'your database goes here';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = 'SELECT title FROM products order by rand() limit 3';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Title: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
2.) Query Using where Clause in this case an id(1) to show product title where id of 1 matches it in the database
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'your password goes here';
$dbname = 'your database goes here';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT id,title FROM products where id='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Title: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Updated Section
First create table below and insert into it
create table products(id int(11) primary key auto_increment,title varchar(30),description varchar(30),image varchar(30),cat_id int(11));
You will insert at least one record
insert into products (id,title,description,image,cat_id) values(1,'product title','product details','product.png',100);
For testing query the products table to get details where id is 1
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'anglejs';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT id,title,description,image,cat_id FROM products where id='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Id: " . $row["id"]. "<br>";
echo "Title: " . $row["title"]. "<br>";
echo "description: " . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now since the Id is coming from url
For testing purpose:
You can save the code as view.php like you did
Open your browser and Enter something like
http://localhost/-----yourfolder diretory goes here-----/view.php?id=1
You can see Id of 1 coming from the Url as appended to view.php files. since we have inserted record which has id of 1, the code below will display the
records only for rows where id is = 1 and so on....
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'anglejs';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$id = $_GET['id'];
//check if id is empty
if($id==''){
echo "Id is empty";
exit;
}
$sql = "SELECT id,title,description,image,cat_id FROM products where id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Id: " . $row["id"]. "<br>";
echo "Title: " . $row["title"]. "<br>";
echo "description: " . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
I am trying to import xml data into a mysql table. I have the below fields to be Imported:
reference
price
category
type
city
property
imgurl1
imgurl2
The problem is that the number of <imgurl>(url to image file) is not the same. Below is the code:
$conn = mysql_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname,$conn) or die( mysql_error() );
$xml = simplexml_load_file('http://astonpearlemail.net/feeds/feedsmall.xml');
$data = $fields = array();
foreach ($xml->xpath('listing') as $listing) {
$fields = array_keys((array)($listing));
$data[] = '("' . join('", "', (array)$listing) . '")';
}
$sql = "INSERT INTO ap_prop (" . join(', ', $fields) . ") VALUES\n" ;
$sql .= join (",\n", $data);
$result1 = mysql_query($sql,$conn);
echo "<pre>$sql</pre>"
Please suggest how I can import the varying number of imgurl.
Thanks in advance
I have a form that allows a user to opt in to receive a notification if a new product comes out. Currently, a users' information is validated and sent to a database. However, I also need it to be sent to an email address.
Both of the scripts work separately; getting them to work together is proving difficult, though.
<?php
//CHECK CAPTCHA IMAGE
session_start();
if( isset($_POST['submit'])) {
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'])) {
// IF CAPTCHA CHECKS OUT, CONTINUE TO VALIDATE DATA.
if( !isset($_POST['fname']) ||
!isset($_POST['lname']) ||
!isset($_POST['email']))
{
echo '<script type="text/javascript">';
echo 'alert("Please go back and fill out the entire form.");';
echo '</script>';
}
// CONNECT TO DATABASE
$dbhost = 'DATABASE NAME';
$dbuser = 'DATABASE USER';
$dbpass = 'PASSWORD';
$dbname = 'DATABASE NAME';
$dbtable = 'TABLE NAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn)
{
die('Could not connect: ' . mysql_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$selected = mysql_select_db($dbname,$conn);
if(! $selected)
{
die('Could not connect: ' . mysql_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$fname = mysql_real_escape_string(stripslashes($_POST['fname']));
$lname = mysql_real_escape_string(stripslashes($_POST['lname']));
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$today = date("Y-m-d H-i-s");
if (mysql_query("INSERT INTO $dbtable(fname, lname, email, date) VALUES('$fname', '$lname', '$email', '$today')") != true)
{
echo ("ERROR: " . mysql_error() . "<br />");
} else {
//echo 'Thank you, your information has been entered into our database. <br />';
}
mysql_close($conn); // CLOSE DATABASE
include('../thankyou.html');
unset($_SESSION['security_code']); //END SESSION
} else // IF CAPTCHA DOESN'T CHECK OUT, DISPLAY ERROR MESSAGE.
{
echo '<script type="text/javascript">';
echo 'alert("Sorry, you have provided an invalid security code.")';
echo '</script>';
}
}
?>
I've tried including a form-to-email script as an "include" and I've tried integrating the two scripts into one, but neither has worked so far.
Any thoughts would be greatly appreciated.. Thank you!
For the email portion, simply use the mail function or, better yet, use one of the well-tested mailer libraries such as PHPMailer and Swift Mailer.
Try using the PHP mail function after you close the mysql connection. For example...
$my_email = Whatever address you'd like this sent to.
$subject = Subject line of email.
$message = The content of the email, this can contain your variables and html formatting if you wish. Something like:
$message = " $time (Central Time) \n
From: $visitor ($visitormail)\n
Message: $notes
";
$headers = The header info, something like:
$headers = "From: $visitormail \r\n" .
"Reply-To: $visitormail \r\n" .
'X-Mailer: PHP/' . phpversion();
...and send the email with...
mail("$my_email", $subject, $message, $headers);
and then you can redirect to another page with:
header( "Location: http://example.com/thankyou.html");
<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$dbname = '';
$dbtable = 'webagents';
//$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
//$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect: ' . mysqli_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$selected = mysqli_select_db($conn,$dbname);
if(! $selected)
{
die('Could not connect: ' . mysqli_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$cname = mysqli_real_escape_string($conn, $_POST['compname']);
$cperson = mysqli_real_escape_string($conn, $_POST['contperson']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
if (mysqli_query($conn,"INSERT INTO $dbtable(compname, contperson, email, phone, country) VALUES('".$cname."','".$cperson."', '".$email."', '".$phone."', '".$country."')") != true)
{
echo ("ERROR: " . mysqli_error($conn) . "<br />");
//die (mysqli_error($myConnection));
} else {
echo 'Thank you, your information has been entered into our database. <br />';
}
mysqli_close($conn); // CLOSE DATABASE
?>
I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>
How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);
If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.
This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>