starting query to display result:
$at = array();
$num=array();
$i=0;
while($rw=mysql_fetch_array($r))
{
echo $rw['c_number']
$number=$rw['c_number'];
$num[$i]=$number;
$i++;
echo $rw['total'];
$at[] = $rw['total'];
}
// the result of this query is like:
Mobile numbers bills
03455919448 34
03215350700 56
03474738923 678
03573987932 344
03187438979 1324
// now want to insert it in database
$d= 'november';
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at','$d','$num')";
mysql_error();
$result = mysql_query($sql);
}
// the insertion query at end is not working and gives me error:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0004 sec )
I think you need to replace num with num1 like
$sql = "INSERT INTO `billing details`(bill,`month/year`,c_number) VALES ('$at','$d','$num1')";
And dont use mysql_* functions due to they are depricated,instead you use mysqli_* functions or PDO statements
AND put your table name in '`' it seems like two different names and for the column name month/year also
i dont know what exactly want to insert $num or $num1 ? and check your table name ,column names
$d= 'november';
int i=0; // you are saying that $at has all bills
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at[i]','$d','$num1[mobile_number]')";
$result = mysql_query($sql);
if (mysql_error()) die('Error, insert query failed');
i++;
}
Related
I have a for loop with php but is not working properly. Inside the for loop I have an "if" and an "else", but the loop stops iterate in the first "else" and should continue. Here is the code:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
} //end of else
} //end of for
The thing is if the database contain 5 rows and I want to insert, for example, 10 rows, the code works updating the first 5 with the new value, then it jumps to the "else" and starts to iterate in the sixth value and it works, but the next values doesn't.
Any idea what i'm doing wrong? Thanks!
Hector
Ok I found the problem. In the else loop, when the iteration tries to select the database, for some reason it takes part of the name of the last iteration, so it couldn't find the database. The solution (maybe is not so clean) is connect and close the database connection in every iteration. The code stays like this:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
// reconnect to db
$con = mysqli_connect($host, $user, $pass) or die ("unable to connect");
$db = "database";
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
//close the connection to db;
$con->close();
} //end of else
} //end of for
Thanks you all for inspiring the answer!
Hector
Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();
Sorry, I'm new to php / mysql. I'm trying to change an existing script to take the results and then insert the value into the database.
This is what I've tried. I'm guessing I'm missing something or the syntax is wrong:
// unique reference number is generated.
// check if it exists or not
$query = "SELECT `ID_UNIQUE` FROM `tbl_referrals`
WHERE `ID_UNIQUE`='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
// We've found a unique number. Lets set the $unique_ref_found
// variable to true and exit the while loop
$unique_ref_found = true;
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
(`ID_UNIQUE`)";
}
}
echo 'Your reference number is: '.$unique_ref;
Ticks are for identifiers, single quotes are for string values:
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
('ID_UNIQUE')";
}
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
I'm trying to pull all the "totalsDate" values from a table "totals" and then either INSERT a new record or UPDATE an existing one based on a variable $date.
//getting all the dates from the totals table and assigning to row
$sqlDate = "SELECT totalsDate FROM totals";
$query = mysqli_query($dbCon, $sqlDate);
//$row = mysqli_fetch_array($query);
while($row = mysqli_fetch_array($query)){
$rowDate = $row['totalsDate'];
//if statement to either update the totals table or create a new record
if($rowDate = $date){
$sqlThree = "UPDATE totals SET lodgements = '$lodgementsAfter' WHERE branch_name = '$branchTest' AND totalsDate = '$date'";
$query = mysqli_query($dbCon, $sqlThree);
}
else {
$sqlFour = "INSERT INTO totals VALUES(NULL, '$branchTest', 0, '$amount', 0, '$date')";
$query = mysqli_query($dbCon, $sqlFour);
}
}
The update part works, however my else statement will never be executed and a new record cannot be entered. I also get this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
I'm a bit confused on using the mysqli_fetch_array and how to actually use the data?
Thanks for any help.
One of the problem is that $query gets overwritten inside the loop; see here:
while($row = mysqli_fetch_array($query)){
// ...
$query = mysqli_query($dbCon, $sqlThree);
// ...
}
You should either a) don't store the result of mysqli_query() at all, or b) choose a different variable name, e.g. $update_res = mysqli_query(...);.
Better yet, use a single query to do both:
INSERT INTO totals VALUES (NULL, :branch, 0, :amount, 0, :date)
ON DUPLICATE KEY UPDATE lodgements = :lodgements
Just make sure the proper unique constraints are defined on the table.
your db query is not correct. You are not getting a good result back from your query. The error is saying it expects the result to be an array and its not. its returning a true of false.
read this mysqli_query
for more help.
do you have access to the db command line? what does the query return. Are you certain your db connection info is correct?
i found it.
$rowDate = $date should be $rowDate == $date or $rowDate === $date
your sql result is an array
$row[0] = "1st result"
$row[1] = "2nd result"
..etc
so theortically if you have more then 1 result, it should be doing multiple updates/inserts. are you seeing that? if its just one result then clearly 2014-02-13, 2014-02-26 are not the same.
$sqlDate = "SELECT totalsDate FROM totals where totalsDate='" . $date . "'";
this will return results, with only records that have $date.
$rowcount=mysqli_num_rows($query);
if ($rowcount) < 1))
{
insert;
}
else
{
update;
}
how to insert random value in to database mysql ?
Ok, when i load this code i will have random number format like this
5,3,1,6,4,
and i want to insert 5,3,1,6,4, into database mysql ( 1 row 1 column) , how can i do ?
<?
$cards = array();
for ($i = 0; $i < 5; $i++)
{
$card = mt_rand(1, 6);
if(!in_array($card, $cards))
{
$cards[$i] = $card;
}
else
{
$i--;
}
}
foreach ($cards as $cards)
{
echo $cards.",";
}
?>
How does it differ from inserting non-random values ?
mysqli_query($link, "INSERT INTO yourtable (id, cards) VALUES (NULL, '$cards')");
Or something similar.
Pure (My)SQL solution:
INSERT INTO test( x, y )
SELECT 10*rand(),
10*rand()
FROM information_schema.columns
LIMIT 10;
Demo: http://www.sqlfiddle.com/#!2/be6e5/2
The easiest way to do what you describe would be as #Martin answered.
However this will probably screw you up later. Ideally you don't want to store a list in a RDBMS field; it defeats the whole purpose of having a database.
If you make a table like
ID, cardPosition, cardID
You can do this:
$insert = $db->prepare("INSERT INTO cardpositions (cardPosition, cardID) VALUES (:cardPosition, :cardID)");
foreach ($cards as $cardPosition=>$card)
{
$insert->execute(array(':cardPosition' => $cardPosition, ':cardID' => $card));
}
OR
The wrong way to do this, but the one you seem to want is:
$cardlist = implode(",",$cards); //now you have a comma separated list without the trailing comma
then you do this if PDO:
$insert = $db->prepare("INSERT INTO cardpositions (cardlist) VALUES (:cardlist)");
$insert->execute(array(':cardlist' => $cardlist));
or this if mysqli:
mysqli_query($link, "INSERT INTO yourtable (cardlist) VALUES ('$cardlist')");