I'm trying to insert in each row of database the variable $num which is an Array. I want to insert each array position in each row of database.
That's the code I have, and in the moment it is inserting the word "Array":
foreach($html2->find('small[class=menu-item__label__count]') as $aholder) {
$holderdes=$aholder->outertext;
}
preg_match_all('!\d+!', $holderdes, $num);
//preg_match_all('/(\([0-9]+)\)/', $holderdes,$num);
echo print_r($num);
echo("<script>console.log('PHP: ".$num."');</script>");
$insert="INSERT into spec_insert(designers) VALUES ('".$num."');";
$sql=mysql_query($insert);
if ($sql === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " ;
}
}
If you want to insert each array value to a specific column of DB table spec_insert then can use foreach() to retrieve the index value of array. Example
foreach($num as $val):
if(is_array($val)):
foreach($val as $v):
$insert="INSERT into spec_insert(designers) VALUES ('".$v."');";
$sql=mysql_query($insert);
endforeach;
else:
$insert="INSERT into spec_insert(designers) VALUES ('".$val."');";
$sql=mysql_query($insert);
endif;
endforeach;
Related
so i tried to get data from my database to checkbox and this is what i have tried :
<?php
$query = "SELECT * FROM siswa WHERE id_tingkatan='$idtingkatan'";
$result = $koneksi->query($query);
while($row=$result->fetch_assoc()){
?>
<input type="checkbox" name="murid[]" value="<?php echo $row['id_siswa']; ? >"><?php echo $row["nama_siswa"]; ?><br><br>
<?php } ?>
and save the value of checked checkbox into database, this is what i have tried :
if(isset($_POST["submit"]))
{
if(!empty ($_POST['murid']))
{
$i= 0;
foreach($_POST as $murid){
$kelas = $_POST['kelas'];
$murid = $_POST['murid'][$i];
$query = "INSERT INTO murid (id_kelas, id_siswa) VALUES ('$kelas', '$murid')";
$q = mysqli_query($koneksi, $query) or die (mysqli_error($koneksi));
$i++;
}
}
else
{
echo "<script type= 'text/javascript'>alert('Pilih minimal 1 siswa');</script>";
header('Location: ./kelas.php');
}
}
when i submit it does input to database but theres one extra row with id_siswa value as 0
The code inserts one record for each value in $_POST. However, $_POST contains all parameters sent (including submit), not just the checkbox array to be inserted. Iterate over the checkbox array $_POST['murid'] instead.
Change
foreach($_POST as $murid) ...
To
foreach($_POST['murid'] as $murid) ...
I am trying to update some rows in mysql based on selected checkbox,but my query is updating all the rows in the table. Please check below code:
if (!empty($_POST['checkbox']))
{
// Loop to store and display values of individual checked checkbox.
foreach ($_POST['checkbox'] as $selected) {
$sql1="UPDATE Items SET Status='1' WHERE Item_Id='$selected'";
$result1=mysql_query($sql1);
if (!$result1)
{
echo "Error While updating";
}
else
{
header("Refresh: 2;url=Main_Menu.php");
mysql_close($conn);
echo "<p>Todays Menu Updated <a href='Main_Menu.php>Click here</a> if you are not redirected automatically in 2 seconds<br /></p>";
}
}
Here if (!empty($_POST['checkbox'])) you should use the name of your checkbox.
For instance, if your html is like below:
<input type="checkbox" name="checkbox_name" />
You should write the if statement as below:
if (!empty($_POST['checkbox_name']))
The same holds for the foreach statement and the use of this in your sql statement.
I want to fetch and display the user_id(that is auto-incremented) from my table after a user is successfully registered and his user information are stored in the same table. Here goes my code. I need help on the last few lines.
if(isset($_POST['register']))
{
$fname=$_POST['fname'];
$mname=$_POST['mname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
$address=$_POST['address'];
$pincode=$_POST['pincode'];
$phone=$_POST['phone'];
$sql="INSERT INTO `user`(`f_name`,`m_name`,`l_name`,`email`,`password`,`address`,`pincode`,`phone`) VALUES('$fname','$mname','$lname','$email','$pwd','$address','$pincode','$phone')";
$rs=mysql_query($sql);
if($rs==1)
{
echo 'You have been registered successfully!';
}
else
{
echo "Registration failed!";
}
}
$src="SELECT `user_id` from `user` where `email`=$email";
$res=mysql_query($src);
$row=mysql_fetch_field($res);
echo $row;
echo $row[0];
$row is an array of fields, even if in your case it contains only one element. For example, if you use
SELECT a, b, c FROM ...
then $row is an array of 3 elements, $row[0] being for a, $row[1] for b, etc.
mysql_fetch_field — Get column information from a result and return as an object.
$row=mysql_fetch_field($res,0);
if(!row)
{
echo "There is no record";
}
else
{
echo $row->user_id;
}
Check Manual here
I have the code below. I take with post some variables from another page. Then I run my query and I store them to the table materials. Then I select for this table in order to take materialsid and then I want with insert into to store the value of materialsid in another table called material_damages
<?php
session_start();
if(isset($_POST['submit'])) {
include('dbConfig.php');
$mname1=$_POST['name1'];
$mcost1=$_POST['cost1'];
$mquantity=$_POST['quantity'];
$res=mysql_query("INSERT INTO materials VALUES (NULL, '$mname1', '$mcost1','$mquantity')");
if ($res)
{
echo "Insert successful";
}
else
{
echo "Insert failed";
}
$res1=mysql_query("SELECT * FROM materials");
while ($row = mysql_fetch_array ($res1))
{
$id10=$row['materialsid'];
$id11=(int)$id10;
$res2=mysql_query("INSERT INTO damage_materials (damage_materials_id,damage_id,materials_id) VALUES (NULL,NULL,'$id11')");
if($res2)
{
echo "CORRECT";
}
else
{
echo "FALSE";
}
}
}
?>
The material is stored at table materials but the id does not get stored in the table damage_material. It prints Insert succesful FALSE FALSE FALSE FALSE (false is as the number of my materials)
Any ideas?
I've researched this for two days and just about have it working... trouble is, when I check TWO checkboxes on my dynamically populated form, I get FOUR records inserted. It gets weirder... ONE of the records is unique. THREE have the same information. I'm totally lost here.
Here is the code for the form:
<form name="form1" id="form1" method="post" action="insert_zip_codes.php?u=<?php echo $_SESSION['username'] ?>">
<table class="bordered" cellspacing="0">
<tr><th>City</th><th>State</th><th>ZIP Code</th></tr>
<?php while($row = mysql_fetch_array($rs)) { ?>
<tr><td><input name="zip_code[]" type="checkbox" id="zip_code" value="<?php echo $row[zip_code] ?>" /></td><td><?php echo $row[city] ?></td><td><?php echo $row[state] ?></td><td><?php echo $row[zip_code]?></td></tr>
<?php } ?>
</table><br />
<input type="submit" name="Submit" value="Submit" />
</form>
Here is the code for the insert statement on the next page.
<?php $u = $_GET['u']; ?>
<?php var_dump($_REQUEST); ?> </br> </br>`
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);
}
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); ?>
When I hit submit, the following prints out and it inserts successfully into the database.
["zip_code"]=> array(2) { [0]=> string(5) "97477" [1]=> string(5) "97478" }
Looks right, right? But then the database gets these records...
id 40 username *** zip_code 97478
id 41 username *** zip_code 97478
id 42 username *** zip_code 97478
id 43 username *** zip_code 97477
As you can see, the darned thing is entering the first zipcode checked on the page only once (as the fourth record) but is entering the SECOND zipcode first THREE TIMES.
Any idea why? I'm at a loss.
Thank you in advance!!! :)
You are calling mysql_query() 3 times, and with 2 of them outside your foreach() loop, it will insert the last $query/$zip_code an additional 2 times.
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query); // 1st time (does query foreach zip_code)
}
if(mysql_query($query)) // 2nd time (does query on last zip_code a second time)
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); // 3rd time (does query on last zip_code a third time) ?>
Removing the last one, as it is just there for de-bugging, you could change your loop code to -
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
$result = mysql_query($query);
if($result)
{
echo 'success ';
}
else
{
echo 'failure' .mysql_error();
}
}
The problem relates to your use of mysql_query() and the $query variable you are using.
Here's a walk through.
You submit two postcodes via $_POST
You loop through the $_POST array and set $query to be the INSERT string.
You then pass that into the function mysql_query() to execute the command to INSERT the record.
So now, you've got two records in your database. You didn't do any checks to see if they worked individually as inserts during that loop (you should have). You also didn't do any escaping to avoid dodgy injection tampering. (you should have).
Anyway, after your loop, this is where it all goes wrong. You then check to see if it worked by running mysql_query($query) again. This is actually going to run the last $query INSERT string you generated again as a command. So that inserts another record into the table.
THEN, you do something with the variable $results by yet again, running the mysql_query($query) command. So that's another record you've inserted.
This means you would have 4 records inserted into your table.
A suggestion
This is off the top of my head! - not tested it
$u = "Whatever";
$inserted = 0;
$fatal = Array();
foreach($_POST['zip_code'] AS $z){
if(mysql_query("INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".mysql_real_escape_string($z)."')";
$success += mysql_affected_rows();
} else {
$fatal[] = mysql_error();
}
}
echo "Inserted $success of ".count($_POST[zip_code])." records.<br />";
if(count($fatal)){
$fatal = array_unique($fatal);
echo "The following error(s) occurred:<br />";
print "<pre>";
print_r($fatal);
print "</pre>";
}
Hope that helps in some way!