The below script works fine but only for the first record in the array.
$codes = array(1,2,3,4,5,6,7,8,9,10); // demo for this question, i actually have 1000+
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect1: ' . mysql_error());
}
$con2 = mysql_select_db("db", $con);
if (!$con2)
{
die('Could not connect2: ' . mysql_error());
}
$productsid = "select `products_id` from `coupons_products` where `coupons_id`=58386264";
$productsquery = mysql_query($productsid);
foreach ($codes as $code) {
while ($productid = mysql_fetch_assoc($productsquery)){
$sql = "insert into discount_coupons_to_products values (
'$code',
'{$productid['products_id']}')";
$con4 = mysql_query($sql);
if (!$con4)
{
die('Could not connect4: ' . mysql_error());
}
}
} // end foreach
I have an array of codes from the database that need apply only to specific products(same as 58386264). The codes works but only for the first coupon in the array ($codes).
If I understand what it means, you will need to run mysql_query command every step inside foreach, not just run mysql_fetch_assoc like you're actually doing.
Related
I have been trying for the past while to echo out the result of a a MySQL query in PHP. I can't seem to get it to work so I am a bit lost. I know for a fact that the query works as I have done it in PHPMYADMIN and it is working fine, however whenever I load the webpage, nothing is outputted. For the purposes of this question I have generalized the things in the query as I obviously don't want anyone accessing my database. This is what I have tried:
<?php
$connect = mysql_connect('host', 'user', 'password', 'dbname');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('dbname')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT SUM(row name) FROM `table`');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($connect);
?>
I look forward to your replies.
mysql_result need the second parameter (The row number from the result that's being retrieved).
echo mysql_result($result, 0);
you have to change
echo mysql_result($result);
by
echo mysql_result($result,0);
or you can use
print_r(mysql_fetch_assoc($result));
Try this
echo mysql_result($result,0);
For more information, please give a look on http://www.php.net/mysql_result
or you can use mysql_fetch_row instead of mysql_result.
$row = mysql_fetch_row($result);
echo $row[0];
You may use this following format:
Give your Sql command like this:
$result = mysql_query('SELECT SUM(row name) as new_column_name FROM `table`');
then use this loop
while($fetched_values = mysql_fetch_array($result)){
echo $fetched_values['new_column'];
}
In your mysql_connect you have provided 4 parameters. it accepts 3 params
host, username and password. dbname is given inside mysql_select_db
as you can see from official docs. So remove the 4th param from mysql_connect function.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
http://php.net/function.mysql-connect
$db_selected = mysql_select_db('foo', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
but these mysql_* function will be deprecated use mysqli instead.
pass a row number as second parameter in mysql_result
echo mysql_result($result, 1);
or
use print_r(mysql_fetch_array($result));
where $result is your result resource
if you have any doubt you may refer my following example program.
<?php
$connect = mysql_connect('localhost', 'user_name', 'password', 'db_name');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name'))
{
die('Could not select database: ' . mysql_error());
}
$row = mysql_query('SELECT (Tamil+English+Maths) as total FROM table_name');
if (!$row)
{
die('Could not query:' . mysql_error());
}
while($fetched_row = mysql_fetch_array($row)){
echo $fetched_row['total'];
}
mysql_close($connect);
?>
here Tamil,English and Maths are the column values of my table
I have written below to extract data from webpage, but this is running continuously with out inserting data into table. How do I split this trancation in below code.
I want to insert for each url immediately and commit in loop. This is not working:
<?php
// example of how to use basic selector to retrieve HTML contents
ini_set('log_errors','0');
ini_set('display_errors','1');
error_reporting(2047);
include('simple_html_dom.php');
include('parameters.php');
// get DOM from URL or file
set_time_limit(0);
$site_name="sitename";
mysql_connect($hostname, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($database);
$query="select site_name,category,subcategory,link,first_no,last_no
from `search_links` where site_name='".$site_name."'";
echo $query;
$res=mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
$links[]=array(
"site_name"=>$row["site_name"],
"category"=>$row["category"],
"subcategory"=>$row["subcategory"],
"url"=>$row["link"],
"first_no"=>$row["first_no"],
"last_no"=>$row["last_no"]);
}
foreach ($links as $link)
{
for ($i=$link["first_no"];$i<$link["last_no"];$i++)
{
try
{
$html = file_get_html($link["url"].$i);
$sql = array();
foreach($html->find('a') as $e)
{
$sql[] = "('".$e->href."',
'".$site_name."',
'".$link["category"]."',
'".$link["subcategory"]."','N')";
}
#var_dump($sql);
mysql_connect($hostname, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($database);
$sql_ext=" ON DUPLICATE KEY update duplicate='Y'";
/*//echo('INSERT INTO table (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql));*/
mysql_query(
'INSERT INTO classifieds (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql).$sql_ext);
mysql_query("COMMIT");
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
}
}
?>
mysql extension does not throw exceptions.
so, either use regular error reporting
$sql = 'INSERT INTO classifieds (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql).$sql_ext;
mysql_query($sql) or trigger_error(mysql_error().$sql);
or throw an exception this way
if (!mysql_query($sql)) {
throw new Exception(mysql_error().$sql);
}
I have the following code that is supposed to call a function in a loop, and then pass the argument to it and put the selected items in a database. I don't think I am passing the correct arguments through to the function though, so can you have a look?
<?php
function welcome($grill){
$link = mysql_connect('localhost', 'sc2brsting', '1A2');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sc2bring1', $link);
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ($grill)";
mysql_query($sql);
mysql_close($link);
}
?>
<?php
$grass=0;
while($grass<500){
$file = $DOCUMENT_ROOT . "website.com";
$doc = new DOMDocument();
#$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('a');
for ($i=106; $i<=204; $i=$i+2)
{
$grill = $elements->item($i)->nodeValue . " ";
welcome($grill);
}
$grass=$grass+24;
}
?>
the problem im having is that the variable $grill isn't passing through the function
You are not escaping the variable $grill when inserting it into to database.
This will cause an MySQL error, hence the impression the argument is not passed to the function.
The line should look like this:
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ('".$grill."')";
I am trying to insert data in table in mysql database through php code but I am always getting following error:
Invalid query: Table 'whatsup_wp1.pushDevices' doesn't exist
I am using following code:
<?php
$deviceid = $_GET["deviceid"];
$link = mysql_connect('localhost', 'whatsup_wp1', 'XSvUCl0FugzV4');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('whatsup_wp1', $link);
if (!$db_selected) {
echo 'Can\'t use whatsup_wp1 : ' . mysql_error();
}
else
{
//echo 'connect';
}
//$query = "select count(*) from city";
//$query = "insert into devices (pushID) values('".$deviceid."')";
$query = "INSERT INTO pushDevices(device) VALUES ('".$deviceid."')";
echo $query;
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
echo $result;
?>
This database have more tables and I am able to use them. I am having problem with the tables that I am creating today. They appears in phpmyadmin but somehow I am not able to get use them through my php code.
Any help may be vital for me. I have spent complete day on it.
Thanks
Pankaj
Its hard to tell by What your saying but i have a suggestion.... It looks like theres no table selected try this
it formatted like this
$query = "INSERT INTO mydb.mytable
(mytablefield)
VALUES
('myfieldvalue')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
My guess is you meant for it to be like this?
$query = "INSERT INTO whatsup_wp1.devices
(device)
VALUES
('".$deviceid."')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
And for security reasons i recommend this...
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Change to
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Personally i just use it like this
$result = mysql_query("INSERT INTO mytable
(mytablefield)
VALUES
('myfieldvalue')");
if($result){echo "Works!";}
else{die('Invalid query: ' . mysql_error());exit();}
If you are on Linux, check that the case is the same.
On windows MySql is case insensitive, on Linux, it is case sensitive.
Also, you are missing a space after pushDevice: pushDevice(...
I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
I want to modify it so that items will be extracted from my db.
Here is how items should be :
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
The query is just:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>