I'm trying to go threw my table nonbulkmdu and look into r10database to find if there is a duplicate, if there is it will update 4 fields if its not it will insert a new row. I keep getting the error
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in on line 19-23.
What am I doing wrong?
<?php
$username="";
$password="";
$database="";
$link = mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM nonbulkmdu";
if ($result=mysql_query($query, $link)) {
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$address=strtoupper(mysql_result($result,$i,"address"));
$drops=mysql_result($result,$i,"drops");
$city=mysql_result($result,$i,"city");
$citycode=mysql_result($result,$i,"citycode");
$feature_type=mysql_result($result,$i,"Feature_Type");
$result = mysql_query("update r10_database
set drops=$drops, citycode=$citycode, city=$city, Feature_Type=$feature_type
where address=$address;");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ($address,
$drops,
$city,
$citycode,
$Feature_Type);");
}
$i++;
}
} else {
echo mysql_error();
}
mysql_close();
?>
You're missing quotes around the values in the UPDATE and INSERT call:
$result = mysql_query("update r10_database
set drops='$drops', citycode='$citycode', city='$city', Feature_Type='$feature_type'
where address='$address';");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ('$address',
'$drops',
'$city',
'$citycode',
'$Feature_Type');")
BTW, if address has a unique key in the table, you can do both queries at once, using INSERT ... ON DUPLICATE KEY UPDATE.
Related
i am trying to insert a data. But i am getting an error and i can't solve it any help will be really appreciated
Error: Warning: mysqli_num_rows() expects parameter 1 to be
mysqli_result, boolean given
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error());
if ($insert_qryy->num_rows==0)
{
echo "Error";
}
else
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`(`purpose`, `property_type`, `city`, `title`, `description`,
`property_price`, `land_area`, `expires_after`, `property_img`) VALUES('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."',
'".$landarea."','".$expiry."','".$im."')") or die (mysqli_error());
}
it is entering the $insert_qryy data but the second statement is not working If statement is getting false i hope I'll get my solution here
As you said - No i want to insert the data of second query if first query have inserted its data.check this once:-
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if ($insert_qryy)
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
} else{
echo "First Insert not executed properly";
}
Note:- Problem is Insert query return a boolen value true or false, based on query executed or not. So you can not use it directly in mysqli_num_rows(), because it ask for a result-set object as parameter not a boolean value.
For checking INSERT query status you can use mysqli_affected_rows or mysqli_insert_id().
$lastid = mysqli_insert_id($link);
Modified example:
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values ('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr. "','".$country."','".$dob."')")
or die(mysqli_error());
$lastid = mysqli_insert_id($con);
if (intval($lastid) <= 0)
{
echo "Error";
}
else{
// your second query or success.
}
Use mysqli_affected_rows () function to check if data is inserted successfully into table
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if (mysqli_affected_rows() > 0) //use this to check if data is inserted successfully into table
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
}
else
{
echo "something went wrong!!! at first query insertion";
}
I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
This is for a registration form I have created. I cannot include all of my code, but the program checks for blank fields then format using the preg_match function. Then it INSERTS the info registered
My code is:
<?php
/* connection info */
ini_set('include_path','../../includes');
include("dbinfo.inc");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die("Couldn't connect to server. error 3");
?>
<?php
/* Program name: Register.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
// Insert info into database //
{
foreach($good_data as $field => $value)
{
$good_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "INSERT INTO UserInfo (user_id, password, first_name, last_name, city, country, email) VALUES ('$good_data[user_id]', '$good_data[password]', '$good_data[first_name]', '$good_data[last_name]', '$good_data[city]', '$good_data[country]', '$good_data[email]')";
$result = mysqli_query($query, $sql) or die ("Couldn't connect to login");
$row = mysqli_fetch($result);
while ($row = mysql_fetch_assoc($result)) {
$sql2 = "UPDATE TimeStamp SET time = CURRENT_TIMESTAMP where user_id='$good_data[user_id]'";
$result2 = mysqli_query($cxn,$sql2) or die("<p>Couldn't Connect to Login</p>");
include('goodReg.inc');
}
{
echo $message;
extract($good_data);
include('register.inc');
exit();
}
}
}
else
{
include("register.inc");
}
?>
How do I move just the variable to the query and not the whole INSERT string?
There's no need to call mysqli_fetch or mysqli_fetch_assoc. Just do the UPDATE query outside of a loop:
$sql = "INSERT INTO UserInfo (user_id, password, first_name, last_name, city, country, email) VALUES ('$good_data[user_id]', '$good_data[password]', '$good_data[first_name]', '$good_data[last_name]', '$good_data[city]', '$good_data[country]', '$good_data[email]')";
mysqli_query($cxn, $sql) or die ("Couldn't insert into UserInfo: " . mysqli_error($cxn));
$sql2 = "UPDATE TimeStamp SET time = CURRENT_TIMESTAMP where user_id='$good_data[user_id]'";
mysqli_query($cxn, $sql2) or die ("Couldn't update TimeStamp: " . mysqli_error($cxn);
include('goodReg.inc');
I need to insert the details (name, id , number )of many documents into database if they are not already existing and if they exist i just need to do a update for any changed information. I have arrived at the following code but it doesn't work. I am new to this and need help on this.
foreach($A->Documents -> Document as $Document)
{
$query = "SELECT * from table where id = '".$Document->id."'";
$outcome = mysql_query($query) or die(mysql_error());
if(($outcome)&&(mysql_num_rows($result)>0)){
echo "Document already available" ;
while($row = mysql_fetch_object($outcome)){
if(!($outcome->name == $document->name)){
$update= "UPDATE table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
else
{
$insert= "INSERT table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
}
}
}
Use $row->name instead of $outcome->name. and your INSERT statement is wrong.
while($row = mysql_fetch_object($outcome)){
if(!($row->name == $document->name)){
$update = "UPDATE table SET name ='".$Document->Name."' WHERE id = ".$Document->id;
mysql_query($update) or die(mysql_error());
}
else {
$insert = "INSERT INTO table (name) VALUES('".$Document->Name."')";
mysql_query($insert) or die(mysql_error()); // $insert not $update
}
}
Note: Stop using mysql_* functions! Use PDO or mysqli_* instead. And use prepared statements
Change the
mysql_query($update) or die(mysql_error());
To:
$insert = INSERT into table_name values(" values");
mysql_query($insert) or die(mysql_error());
in the else condition
Issue is with $result variable with in if statement
( if(($outcome)&&(mysql_num_rows($result)>0)){)
It should be $outcome because you initialized query output to $outcome variable
First of, dont yse mysql_ functions. Read the docs (read the warning).
use mysqli or PDO instead.
Then, your INSERT statement is wrong.
INSERT INTO table (col1) VALUES (value_for_col1);
This is a code for a cafeteria, and this is the login.
<?php
$userna = 'root';
$paso = '';
$mach = 'localhost';
$db ='cafeteria';
session_start();
// GET PAGES RECORD FROM LOG TABLE: *********| Only the first time though:
if (isset($_SESSION['log']) != 'logging')
{
// Here, just creating a string:
$pages_record = "";
$insert_query = '';
// Get saved pages from the database:
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Error in log-page script: AB-1 - query: $insert_query." . mysqli_error($connection));
mysqli_select_db($connection,'cafeteria');
// Query string to pull all pages from table record:
$get_pages_query = "select * from log-page";
// Query the database, and save result:
$query_pages_result = mysqli_query($connection, $get_pages_query);
// Check number of results returned:
$num_of_results = '';
$num_of_results = mysql_num_rows($query_pages_result);
if ($num_of_results > 0)
{
// Loop through the result array: Each time, one row, and then the next one ...
for ($row = 0; $row < $num_of_results; $row++ )
{
// Getting one row:
$get_row = mysqli_fetch_array($query_pages_result);
// Extracting just the page name from the row:
$one_page = substr($get_row["page"],strripos($get_row["page"],"/") + 1);
// Adding this page name to the string created previously:
if ($row == 0)
{
$pages_record .= $one_page;
}
else
{
$pages_record .= ",".$one_page;
}
}
// Once all pages have been read and saved to the string
// now we save it to the session:
$_SESSION['logpages'] = $pages_record;
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
else
{
// There are no pages in the table:
$_SESSION['logpages'] = "";
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
}
// Check if page is already in session list.
$pages_array = array();
if (strlen(isset($_SESSION['logpages'])) > 0 )
{
// string variable that holds all pages separated by commas:
$pages_string = $_SESSION['logpages'];
// creating an Array to hold all pages already logged in server:
if (strstr($pages_string, ","))
{
$pages_array = explode(",", $pages_string);
}
else // just means there's only one page in the record
{
// so, we push it inside the array.
array_push($pages_array, $pages_string);
}
// current page: [ We are extracting only the page, not the entire url, Exmp: login.php ]
$current_page = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Check if current_page is in the array already:
if (!in_array($current_page, $pages_array))
{
// IF is NOT in the array, then add it:
array_push($pages_array, $current_page);
// Add it to the Session variable too:
$pages_string = implode(",", $pages_array);
// Re-save it to SESSION:
$_SESSION['logpages'] = $pages_string;
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(`date`, `time`, `page`, `user`) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection, $insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
else
{
// IF it IS in the list, just SKIP.
}
}
else
{
// means, that there are absolutely no pages saved in the database, basically this is the first log:
$_SESSION['logpages'] = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(date, time, page, user) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection,$insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
?>
But now i am getting this error:
Error in log-page script: AB-2 - query: INSERT INTO log-page (date,
time, page, user) VALUES ('2012-10-16', '16:58:44',
'/caf/pages/index.php', '').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 '-page (date, time, page, user)
VALUES ('2012-10-16', '16:58:44' at line 1
Im using Xampp 1.8.1 PHP: 5.4.7. It does not let me login neither as administrator nor as a cashier
Enclose the table name in backticks like this (rest of the query omitted):
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) ... ";
Otherwise MySQL will try to interpret the - as a minus sign, which fails in this case.
EDIT
IN the last insert shown, also the column names should be enclosed in backticks:
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) VALUES ...";
Try escaping field name
(`date`, `time`, `page`, `user`)
It's been a while since I looked at mySql docs, but it looks to be complaining about the table name "log-page". Try quoting that table name.