Can you tell me why my code isn't working ? In my username table I have two columns, user_id and username. user_id is auto increment so I don't have that in my Sql statement, which I believe is the correct thing to do.
<?php
require('dbConnect.php');
$Number = $_POST['phonenumber'];
// The ? below are parameter markers used for variable binding
// auto increment does not need prepared statements
$query = "INSERT INTO user (username) VALUES (?)";
$stmt = mysqli_prepare($con,$query) or die(mysqli_error($con));
//bind variables
mysqli_stmt_bind_param($stmt,"s",$u);
//$stmt->bind_param("s",$u);
mysqli_stmt_execute($stmt);
if(mysqli_query($con,$query))
{
echo 'Inserted correctly';
}
else
{
echo 'Error';
echo var_dump($stmt);
}
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
I keep getting 'Error', and in my var_dump I get :
C:\wamp64\www\phpproject\php-project\insert.php:28:
object(mysqli_stmt)[2]
public 'affected_rows' => int -1
public 'insert_id' => int 0
public 'num_rows' => int 0
public 'param_count' => int 1
public 'field_count' => int 0
public 'errno' => int 1048
public 'error' => string 'Column 'username' cannot be null' (length=32)
public 'error_list' =>
array (size=1)
0 =>
array (size=3)
'errno' => int 1048
'sqlstate' => string '23000' (length=5)
'error' => string 'Column 'username' cannot be null' (length=32)
public 'sqlstate' => string '23000' (length=5)
public 'id' => int 1
use null for autoincrement like this
$query = "INSERT INTO user (user_id,username) VALUES (null,$username)";
Related
So I have been doing my research and no method seems to parse my file correctly. I have tried these two codes, my data is being inserted into sql however it is inserted 3 times with the first insertion being fine while the other 2 are blank. Here is my JSON file and code:
JSON:
[
{
"Comments": {
"Manufacturer": "--E",
"Model": "----- ----- ----",
"BIOSFamily": "---",
"BIOSDate": --/--/---8",
"SerialNumber": "---------"
}
},
{
"#ComputerSystem.v1-----------ystem": {
"/redfish/v1/Systems/1/": {
"AssetTag": " ",
"Bios": {
"#odata.id": "/redfish/v1/systems/1/bios/"
},
"BiosVersion": "U----------------)",
"Boot": {
"BootSourceOverrideMode": "-----y",
"BootSourceOverrideTarget": "None",
"BootSourceOverrideEnabled": "Disabled",
"BootSo-----------arget#Redfish.AllowableValues": [
"None",
"Cd",
"Hdd",
"Usb",
"Utilities",
"Diags",
"BiosSetup",
"Pxe",
"UefiShell"
]
Code:
<?php
$connect = mysqli_connect("reserve1",
"root", "","server_31");
$filename = "-----.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO servers (Model,
Manufacturer, BIOSFamily,
BIOSDate,
SerialNumber) VALUES
('".$row["Comments"]["Model"]."' ,
'".$row["Comments"]
["Manufacturer"]."',
'".$row["Comments"]
["BIOSFamily"]."','".$row["Comments"]
["BIOSDate"]."','".$row["Comments"]
["SerialNumber"]."')";
mysqli_query($connect, $sql);
}
echo "Data in";
?>
ERROR:" Notice: Undefined index: Comments "
other forloops i have tried are:
foreach($data as $Comments)
{
$sql =" INSERT INTO
'servers'('Manufacturer','Model',
'BIOSFamily','BIOSDate',
'SerialNumber'), VALUES('{$Comments-
>Manufacturer}', '{$Comments-
>Model}',
'{$Comments->BiosFamily}',
'{$Comments->BiosDate}',
'{$Comments-
>SerialNumber}')";
}
ERROR:" Notice: Trying to get property of non-object in"
To reiterate: the first method does get my info onto sql but does so 3 times with the last 2 entries being blank. The second method does not insert anything into my table.
EDIT:
so i tried vardump, using the file itself all i got was NULL, copy and pasting the contents and labeling it $json= ' content ' in the script i get..
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
0 =>
object(stdClass)[1]
public 'Comments' =>
object(stdClass)[2]
public 'Manufacturer' => string 'HPE' (length=3)
public 'Model' => string '-------------' (length=20)
public 'BIOSFamily' => string '---' (length=3)
public 'BIOSDate' => string '--/--/----' (length=10)
public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
0 =>
array (size=1)
'Comments' =>
array (size=5)
'Manufacturer' => string '---' (length=3)
'Model' => string '------ ----------' (length=20)
'BIOSFamily' => string '---' (length=3)
'BIOSDate' => string '--/--/----' (length=10)
'SerialNumber' => string '-------' (length=10)
Simply index in your foreach loop the first item since $array object maintains Comments only in first position. See 0 index from var_dump output:
array (
0 =>
array (
'Comments' =>
array (
'Manufacturer' => '--E',
'Model' => '----- ----- ----',
'BIOSFamily' => '---',
'BIOSDate' => ' --/--/-- - 8 ',
'SerialNumber' => '---------',
),
),
1 =>
array (
'#ComputerSystem.v1-----------ystem' =>
...
Therefore, iterate through the Comments array and use parameterization for readability:
$connect = new mysqli($servername, $username, $password, $dbname);
// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
VALUES(?, ?, ?, ?, ?)";
// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) {
$stmt = $connect->prepare($sql);
// BIND PARAMETERS (NO COMMENTS INDEX)
$stmt->bind_param("sssss", $row["Model"],
$row["Manufacturer"],
$row["BIOSFamily"],
$row["BIOSDate"],
$row["SerialNumber"]);
// EXECUTE STATEMENT
$result = $stmt->execute();
}
I have a Collection of Colle Object in a form and I want to access id of each colle.
I tried :
$colles = $data['colles'];
Dump of $colles :
array (size=2)
1 =>
object(PACES\ColleBundle\Entity\Colle)[4156]
protected 'id' => null
protected 'nom' =>
object(PACES\ColleBundle\Entity\ColleQC)[4126]
private 'questions' =>
object(Doctrine\ORM\PersistentCollection)[4646]
...
protected 'id' => int 140
protected 'coefficient' => string '1.00' (length=4)
protected 'coefficient' => int 1
2 =>
object(PACES\ColleBundle\Entity\Colle)[4144]
protected 'id' => null
protected 'nom' =>
object(PACES\ColleBundle\Entity\ColleQC)[4583]
private 'questions' =>
object(Doctrine\ORM\PersistentCollection)[4592]
...
protected 'id' => int 150
protected 'coefficient' => string '1.00' (length=4)
protected 'coefficient' => int 1
For 1st object, I want getId() to get 'id' = 140 and for 2nd, 'id' = 150
This code returns null :
foreach ($colles as $colle) {
$idColle = $colle->getId();
}
If you look at the dump of $colles, you see that the 'id' of both 1 and 2 are "null", but it is the 'nom' collection (I think that's the collection) that has the Ids you are looking for.
Did you try:
$idColleNom = $colle->getNom()->getId();
I'm not certain of your setters and getters, but it might be something like that.
i try show data using PDO. But i get Error "Trying to get property of non-object".
i have a simple script.
public function tampilUserId($user_id)
{
$sql = "SELECT $this->user.*, $this->provinsi.*
FROM $this->user
INNER JOIN $this->provinsi
ON $this->user.provinsi_id=$this->provinsi.provinsi_id
WHERE user_id=:user_id";
$stmt = db::prepare($sql);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
And this
echo $results->email_user;
print_r($result);
result
Notice: Trying to get property of non-object in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
And i try this script
echo $results['email_user'];
print_r($results);
result
Notice: Undefined index: email_user in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
Please help me, thanks before.
Merdeka! :D
In case your SQL query not contain any error its mean data was successfully pulled from database. So in your tampilUserId($user_id) function, its returning set of array from $stmt->fetchAll(PDO::FETCH_OBJ). Like below:
/* Sample from Sakila database */
array (size=603)
0 =>
object(stdClass)[11]
public 'address_id' => string '1' (length=1)
public 'address' => string '47 MySakila Drive' (length=17)
public 'address2' => null
public 'district' => string 'Alberta' (length=7)
public 'city_id' => string '300' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:27' (length=19)
1 =>
object(stdClass)[12]
public 'address_id' => string '2' (length=1)
public 'address' => string '28 MySQL Boulevard' (length=18)
public 'address2' => null
public 'district' => string 'QLD' (length=3)
public 'city_id' => string '576' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:09' (length=19)
more elements...
All you need to do is looping your function returned value first whereever you call it. Short example from your case:
//I dont know you put it under class or not.
$data = $YourClass->tampilUserId($user_id);
foreach ($data as $item) {
echo $item->email_user);
}
Note:
You can manually echoing your data without looping and its bad practice because you dont know the length of the array. So this is just gusessing. Taken from your case it would be.
$data = $YourClass->tampilUserId($user_id);
$data[0]->email_user; //If an object
$data[0]['email_user']; //If an array
Update:
There is suspicious thing on your query. The variable $this->user is not look like column name to me(unsure) If yes, so you have small mistake on your query. Secondly, as you said the result is null its mean something wrong or data you search not exist. I put this sample running inner join query.
Example:
Lets said i had 2 table. 1st is address and 2nd is city
|address table|
|city table|
So your sql query for joining table(from image above) should be:
SELECT adr.address_id, adr.address, adr.district, adr.city_id, c.city_id,
c.city FROM address AS adr INNER JOIN city AS c ON adr.city_id = c.city_id
WHERE c.city_id = 300 #using city id
Output:
Bring it to PHP
<?php
$pdo= new PDO('mysql:dbname=sakila;host=localhost:3306', 'user', password');
$city_id = 300; // manual set
$sql = 'SELECT adr.address_id, adr.address, adr.district, adr.city_id,
c.city_id, c.city FROM address AS adr INNER JOIN city AS c ON
adr.city_id = c.city_id WHERE c.city_id = :city_id';
$stmt = $_this->db->prepare($sql);
$stmt->bindParam(':city_id', $city_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
?>
var_dump($data) giving a result:
Great, as it come as (object(stdClass)) so we can loop it through the array & then accessing it using -> sign.
<?php
$i = 1;
foreach ($data as $d) {
echo '<dl>';
echo '<dt>Adress '.$i++.':</dt>';
echo '<li>Address id: '.$d->address_id.'</li>';
echo '<li>Address: '.$d->address.'</li>';
echo '<li>District: '.$d->district.'</li>';
echo '<li>City id: '.$d->city_id.'</li>';
echo '<li>City name: '.$d->city.'</li>';
echo '</dl>';
}
?>
Result in browser:
Hope this will resolve your problem.
This is my store method which grabs the file and loops through each of the rows:
public function store()
{
$input = Input::file('statuses');
$filename = $input->getRealPath();
$i = 0;
$rows = Excel::load($filename, null, 'ISO-8859-1')->get()->toArray();
foreach($rows as $k => $row)
{
if(!isset($err)) {
if (!$this->repository->create($row))
$err = 'Error importing row ' + $i;
$i++;
}
}
if(isset($err)) {
Flash::error($err);
return Redirect::route('admin.importstatus.index');
}
Flash::success('Statuses Imported!');
return Redirect::route('admin.statuses.index');
}
In my repository, my create method looks like this:
public function create(array $data)
{
// Create the model
$model = $this->model->fill($data);
if ($model->save()) {
return $model;
}
return false;
}
Now, what appears to be happening when I import 6 rows only the final is actually getting inserted into the DB.
If I var_dump in my create method, I am being returned the following:
array (size=7)
'content' => string 'Imported two' (length=12)
'status' => float 0
'user_id' => float 1
'pinned' => float 0
'updated_at' => string '2015-06-28 16:13:22' (length=19)
'created_at' => string '2015-06-28 16:13:22' (length=19)
'id' => int 8
array (size=7)
'content' => string 'Imported three' (length=14)
'status' => float 0
'user_id' => float 1
'pinned' => float 0
'updated_at' => string '2015-06-28 16:13:22' (length=19)
'created_at' => string '2015-06-28 16:13:22' (length=19)
'id' => int 8
array (size=7)
'content' => string 'Imported four' (length=13)
'status' => float 0
'user_id' => float 1
'pinned' => float 0
'updated_at' => string '2015-06-28 16:13:22' (length=19)
'created_at' => string '2015-06-28 16:13:22' (length=19)
'id' => int 8
Notice how each of the ID's are all no. 8 (The next available row in the table). The tables ID is defo AUTO INCREMENT etc so no issues there, I guess its a logic issue? Any ideas?
Seems like you are using the same instance of a model over and over.
Try changing fill():
$this->model->fill($data);
with create():
$this->model->create($data);
With fill() you are only filling the already created model instance with some data. But if you use create() you are first creating a new instance (with a new id), then filling it with data and then saving it.
Important
When using create() you are also persisting it to the database, which means you don't have to save() it manually.
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am trying to get single value from DB with single query. i mean that i already featched all values in one query from that i need to get only one column value.
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query( $connection,"select * from register where password='$log_in_password' AND username='$log_in_username'");
var_dump($query);
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
var_dump($table);
assume columns are
' userid useremail username password Name '
from php
var_dump($query) gives this..
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
var_dump($table) gives this
array (size=1)
0 =>
array (size=5)
'userid' => string '7' (length=1)
'useremail' => string 'demo#gmail.com' (length=16)
'username' => string 'demousername' (length=7)
'password' => string 'demopassword' (length=5)
'Name' => string 'demoname' (length=6)
so help me out with fetching only one column value's record (example insSelect * to select userid)
Your variable $table is an array, so if you want only the userid, you just have to use
$table[0]['userid']
If you want to query only the userid change you query like this :
$query = mysqli_query( $connection,"select userid from register where password='$log_in_password' AND username='$log_in_username'");
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
And the result of $table will be :
array (size=1)
0 =>
array (size=1)
'userid' => string '7' (length=1)
$table will also be an array, and to acces userid you have to use again
$table[0]['userid']
Try this
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query($connection, "select * from register where password='$log_in_password' AND username='$log_in_username'");
$table = null;
while ($row = mysqli_fetch_array($query)) {
$table = $row;
}
print_r($table);