Inserting 2D Values of Array into SQL - sql

Right now, I have looped a form which in the end gives me a 2D Array.
Array 0D
User Arrays 1D
User Fields 2D
Array ( [1] => Array ( [fname] => qweqwe [lname] => qwewqe [email] => qwewqe [age] => wewqe ) [2] => Array ( [fname] => 123123 [lname] => 123123 [email] => 23123 [age] => 23123 ) )
This is an example of what I get when I type in rubbish into my fields.
To check if I could get the values for each form, I used this:
$i = $_POST['number'];
$corporate = $_POST['corporate'];
$x = 1;
print_r($corporate);
while($x <= $i)
{
echo "The first name first name".$corporate[$x]["fname"].".";
}
Using this, I would attain the first name of the first user, followed by the second and so on. This proves that I can get the 2D values from my forms.
What I have to do now is to insert those values into my table. Keep in mind, my 1D contains values of each user. 2D is the values itself.
mysql_query("INSERT INTO students ('fname','lname','email', 'age') VALUES
I have no idea what to put after that. Any help would be appreciated.

You need to add a set of data values to insert. These would be in the form ("Robert","Brown","Robert.Brown#uni.com","34")("Robert","Smith","Robert.Smith#uni.com","33")
What version of PHP are you using?
for php5.3 you could try:
$values = array();
foreach($corporate as $line){
$values[] = "('".implode("','",array_map(function($x){ return addslashes($x); })) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
Otherwise, try:
$values = array();
foreach($corporate as $line){
foreach($line as $i=>$item) $line[$i] = addslashes($item);
$values[] = "('".implode("','",$line) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
To solve the second part of your problem, you need to edit the table definitions and remove the "NOT NULL" definition that sits on each field. Do you have php my admin on the server? you could do it through that by editing the table and fields, otherwise you could run the sql using ALTER TABLE. Let me know if you want more information on that.

Well, using your query, understanding what it means in depth, I finally got it working.
This is the code that I used:
foreach($corporate as $line)
{
$values[] = "('".implode("','",$line) . "')";
echo "<br />";
print_r($values);
$a = implode(",", $values);
echo $a;
}
$query = "INSERT into students (fname, lname,email,age) VALUES $a";
$sql = mysql_query($query);
This works fine on my database, works like a charm.
However, when I try this on my friends DB or an Online DB, I get an error which requires me to give every field a value. For some reason, it cannot enter NULL values.
I'm trying to figure out why, but the gist of my problem has been solved.
If you know what is causing my error, feel free to comment. Thanks.

Related

Extra, blank row from PDO select on Sqlite

This involves a Sqlite database, PHP 7 and PDO. The query code is:
...
$stmt = $pdo->query('SELECT * FROM images');
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
$images[] = [
"image_id" => $row["image_id"],
"date" => $row["date"],
"photographer" => $row["photographer"],
...
];
}
echo $stmt->rowCount() . " rows<br>";
echo count($images) . " images<br>";
var_dump($images);
return $images;
}
(Note: This is based on http://www.sqlitetutorial.net/sqlite-php/query/ . It will be revised soon to do prepared statements, enumerating cols, etc., once the problem described here is solved.)
The echos report "0 rows" and "2 images". The var_dump() outputs:
array(2) { [0]=> array(0) { } [1]=> array(14) { ["image_id"]=> ...
So clearly there's an extra, empty array in the first position in the outer array. In the calling code, which collects the $image array as return value, count($array) gives 2 not 1 (and code expecting name/value pairs in each row breaks).
The problem is, there's only one row in the table. This appears clearly on the command line: sqlite> select * from images; gets one row and:
sqlite> select count(*) as c from images;
1
What's wrong here?
Different array syntax solved it.
$stmt = $pdo->query('SELECT * FROM images');
$images = array();
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
$images[] = array(
"image_id" => $row["image_id"],
"date" => $row["date"],
"photographer" => $row["photographer"],
...
);
}
I'm still not clear on the reason, but this way avoids the anomalous empty row.

fetch image and text from database using joomla 2.5

i have one one issue in fetch image and text from database by module what to do for this issue and i add my table name and field name #__home_service_item this is my table name in that table two field one is image and image_name than i have one error for that question i display my error
Warning: Invalid argument supplied for foreach() in C:\wamp\www\Joomla_2.5.8-Stable-Full_Package\modules\mod_home\tmpl\default.php on line 40
please give me any clue for that problem i also add my code
<?php
defined('_JEXEC') or die('Restricted access');
$items = $params->get('items', 1);
$db =& JFactory::getDBO();
$query = "SELECT id
FROM #__home_service_item
WHERE published = '1'
ORDER BY id DESC";
$db->setQuery( $query, 0 , $items );
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo 'ID: '.$row->id.' </br>';
}
?>
please give one clue
do print_r($rows) and see if any records are returning from the database. I think that you have a problem with your query. If there are no results returning try enclosing your foreach statement with in a try catch or ignore warnings.
Also try to set $db->setQuery($query); instead of $db->setQuery( $query, 0 , $items );
If you just need one row result use $db->loadResult();

Issue in making appear all database table field names

I have this code which i use in order to make appear all the names of a table of a database.
It used to work... but suddenly it won't make appear anything..
Could you please take a look?
I'm working with SQL.
$section = "SELECT * FROM forma";
$res = odbc_exec($connection, $section) or die(odbc_error());
$firstrow = false;
while ($row = odbc_fetch_array($res)){
if (!$firstrow) {
foreach ($row as $column => $value) {
echo "<label> " . $column . "</label>";
echo "<input type='checkbox' name='data[]' value='" . $column . "' /><br/><br/>";
}
$firstrow = true;
}
}
Thanks
This is a fairly nasty way of retrieving the column names for a table. What it is doing is reading all the data in the table, ignoring the result set and only using it for the column names. What is happening however is that the table is empty and so nothing is being returned at all.
You need to amend the query to look at the meta data rather than the table itself. You will need to rework it. This SQL will retrieve the column names for that table for you...
Select Columns.Name
From Sys.Columns
Where Object_Name(Columns.Object_id) = 'forma'
Order By Columns.Column_Id;
After that you will need to rejig your code to take advantage of it.

sql update codeigniter

I am using codeIgniter..
I want to update a table column is_close when id=$ticket_id of my table= tbl_tickets.
I am doing this :-
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
and I have also done this :-
$sql = "UPDATE tbl_tickets SET is_close={1} WHERE id='$title_id'";
$this->db->query($sql);
both are not working,i.e., my table is not updating the value to 1 and also no error is being shown in the broswer. :(
Edited: Included my model part :
function setClosePost($title_id){
$sql = "UPDATE tbl_tickets SET is_close=0 WHERE id='$title_id'";
$this->db->query($sql);
// $data=array(
// 'is_close'=>1
// );
// $this->db->where('id',$title_id);
// $this->db->update('tbl_tickets',$data);
}
My controller :-
function closePost(){
$this->load->model('helpdesk_model');
$this->helpdesk_model->setClosePost($this->input->post('title_id'));
}
first of all use a get method to check if ticket_id is exist or not.
another thing is always use return in your functions in models so you can check them by if(function_name){...}else{...}
then if your get method returned data correctly try
Model Method
public function set_closed($ticket_id){
$this->db->set(array(
'is_close'=>1
)); // pass fields in array
$this->db->where('id',$ticket_id);
$this->db->update('tbl_tickets'); // table name
return true;
}
then check that in your controller
if($this->Ticket_model->set_closed($ticket_id) == true){
echo 'ticket set to closed correctly';
}else{
echo 'there is some error on updating database'.$this->db->error(); // to checkout db error .
}
First, check $title_id before passing:
var_dump($title_id);
Then, try do "select a row with this id" before updating and after.
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
Then, give your table structure.
Just try like this
$sql = "UPDATE tbl_tickets SET is_close='1' WHERE id=".$title_id;
$this->db->query($sql);
just try like this
**function edit($close,$id) {
$sql = "UPDATE tbl_tickets SET is_close= ? WHERE id = ? ";
$this->db->query($sql, array($close,$id));
}**
To handle this type of errors, i mean if reflection is not happen in database, then use below steps to resolve this type of error.
1) use $this->db->last_query() function to print query, using this we can make sure our variable have correct value (should not null or undefined), using that we can make sure also SQL query is valid or not.
2) If SQL query is valid then open phpmyadmin & fire same query into phpmyadmin, it will return error if query columns or table names are invalid.
Use this way, its best way to cross check our SQL queries issues.
I hope it will work.
Thanks
You are trying to update integer(INT) type value, just cross check with your column datatype if that is varchar then you have to put value in a single or double quote.
Like this
$data=array('is_close'=> '1');

How can I tell if I'm at the last result when using WHILE so that I can omit a comma from my output?

I know I can do what I need to do by getting a total records count and if I'm at the last record, don't display a comma but there has to be a better way.
I'm trying to build an SQL statement programatically using values from MySQL.
The code:
$fql="SELECT ";
$result = mysql_query("SELECT field FROM fb_aa_fields WHERE fql_table = '$query'", $conn);
while ($row = mysql_fetch_array($result)){
$get_field = "".$row{'field'}."";
$fql = $fql."$get_field, ";
}
$fql = $fql."FROM ".$query." WHERE owner=".$get_uid."";
It outputs this:
SELECT aid, can_upload, cover_object_id, cover_pid, created, description, edit_link, link, location, modified, modified_major, name, object_id, owner, photo_count, size, type, video_count, visible, FROM album WHERE owner=522862206
The problem is the last comma between "visible" and "FROM". How would you suggest is the best way to make that comma go away?
It's less of a pain to detect whether you're at the first element than the last. You could do like
$i = 0;
while($row =...) {
if ($i++) $fql .= ',';
$fql .= $row['field'];
}
Or, possibly better, defer tacking on fields to the string til the end. There's a built-in function called implode, that you can use to insert the commas between them.
$fields = array();
while($row =...) {
$fields[] = $row['field'];
}
$fql .= implode(',', $fields);