PDO prepare working when i reload the second time the page - php

output JSON is here .when i reload the second time it has new recodes.but when i update the first time it does not have recodes
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=$db', "user", "pass");
foreach($dbh->query('SELECT * FROM `jos_jea_towns` LIMIT 0, 500 ') as $row) {
echo '<pre>' . json_encode($row, JSON_PRETTY_PRINT).'</pre>';
}
$insertObject = $dbh->prepare("INSERT INTO `jos_jea_towns` (id, value) VALUES (:id, :value)");
$insertObject->bindParam(':id', $id);
$insertObject->bindParam(':value', $value);
// insert one row
$id = 433;
$value = 'yyy';
$insertObject->execute();
// insert another row with different values
$id = 434;
$value = 'xxx';
$insertObject->execute();
// insert another row with different values
$id = 435;
$value = 'Samitha';
$insertObject->execute();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
How is this PDO prepare working or is there any problem with my JSON file?

Well, you are selecting first, and updating later. So the first time, you select, before you've added the records, then you add the records.
On the second reload, you've already added the records (from the previous iteration), and so the inserted records are displayed.
To solve, insert first, and select after. That way you can see the changes you've just made.

Related

echo selected SQL row data using PHP

If I collect multiple row data from SQL, I will have to use foreach loop or something else to display that data properly.
How to use these PHP strings without using foreach loop ?
Following is my SQL query
$results = $mysqli->query('SELECT * FROM specs where id in ('.$id1.','.$id2.','.$id3.','.$id4.') ');
It will result data from 4 different rows.
The above code is just an example, below is the exact code I am using in my page.
try{
$pdo = new PDO("mysql:host=localhost;dbname=databse", "user", "password");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt select query execution
try{
$sql = "SELECT * FROM specs WHERE id IN($id1,$id2,$id3,$id4)";
$result = $pdo->query($sql);
$results = $result->fetchAll();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
Currently, the data is displayed using the following
<tr>
<td>Brand</td>
<?php foreach ($results as $result){ ?>
<td> <strong><?php echo $result['brand']; ?></strong> </td>
<?php } ?>
</tr>
There will be total 4 results, I wan to use that 4 results separately.
If the results are
Samsung, Sony, Apple, LG - how can I echo the "Apple" only using PHP string ?
Fetch all the rows. If you have the MySQL Native Driver:
$rows = $results->fetch_all(MYSQLI_ASSOC);
Otherwise, fetch with a loop:
while($rows[] = $results->fetch_assoc());
Then you can access them by row:
echo $rows[0]['brand']; // first row
echo $rows[1]['brand']; // second row
But that's not very useful. If you have something unique that you want to use (I use brand as an example though it's probably not), then just index on that:
$rows = array_column($results->fetch_all(MYSQLI_ASSOC), null, 'brand');
// or
while($row = $results->fetch_assoc()) { $rows[$row['brand']] = $row; }
// then
echo $rows['apple']['model'];

Reading SELECT LAST_INSERT_ID(), which seems to produce an array

I am populating a MySQL database using PHP and SQL languages. The table I am populating is called project. After I add the record to project, I would like to send out an email including the project_id and project_title. I thus need to know the project_id after I populate the project table.
The command: $sql = "SELECT LAST_INSERT_ID()"; is returning an array. I have tried several guesses of what is in the array, without any luck.
public function add_project($project_title, $project_description,
$skill_cat_id, $name_id) {
$dbConn = new DatabaseConn();
$this->name_id = $name_id;
$this->skill_cat_id = $skill_cat_id;
if($this->check_for_duplicates() != null) {
$message = "This Project already exist!";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$sql = "INSERT INTO project "
. "(project_id, project_title, project_start_date, "
. "project_description, skill_cat_id, volunteer_id, response_id, name_id) "
. "VALUES (DEFAULT, $project_title, DEFAULT, "
. "$project_description, $skill_cat_id, DEFAULT, DEFAULT, $name_id)";
try {
$dbConn->exec($sql);
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
$dbConn2 = new DatabaseConn();
$sql = "SELECT LAST_INSERT_ID()";
try {
$statement = $dbConn2->prepare($sql);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
return $result;
}
}
I am expecting the project_id of the project table, yet the command is returning an array.
PDOStatement::fetch() always returns an array, which is one row of the result set. The array is either an ordinal array or a hash array indexed by column name.
It doesn't matter that your query is guaranteed to have one column and one row. It's still a result set, for which fetch() returns an array. The array it returns will have one entry, corresponding to the single column of your query.
If you want to return just one column as a scalar, try PDOStatement::fetchColumn().
See the documentation for description and a code example.
You can get last insert Id from the pdo object itself. https://www.php.net/manual/en/pdo.lastinsertid.php

Using foreach loop to update MySQL table with array of IDs

I'm trying to update a MySQL table with three columns (id, franchise_id, state_id) with data from an array by using a foreach loop. The table updates but the four rows that match the franchise_id are being updated with the last item in the array (4). I can't figure out where the error is.
Data passed to the function:
$states = [1,2,3,4];
$franchise_id = 5;
The update function:
public static function update($franchise_id, $states)
{
try
{
// establish db connection
$db = static::getDB();
$sql = "UPDATE franchise_states SET state_id = ? WHERE franchise_id = ?";
$stmt = $db->prepare($sql);
foreach($states as $state)
{
$stmt->execute([$state, $franchise_id]);
}
return $stmt;
}
catch (PDOException $e)
{
echo "Error updating franchise data: " . $e->getMessage();
exit();
}
}
I appreciate any help.
Thanks!
Actually it's updating for all the values in $states array but the last one stays because, well, it is the last executed one.
You try to update state_id against the same value franchise_id=5 and since all of them has the same franchise id, the last value stays.
Have you try to edit this line?
foreach($states as $state)
to
foreach($state as $states)

PHP PDO error undefined index serial

I'm about to pull my hair out. I can't get the undefined index to go away. Basically where it says echo htmlspecialchars($r['serial']) I want it to list the item out of the database table.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->setFetchMode(PDO::FETCH_OBJ);
while ($r = $q->fetch());
} catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
$r = $q->fetchAll();
echo htmlspecialchars($r['serial'])
?>
You are referring to the result as an associative array where you expect to have the key 'serial'. This is the behavior of PDO::FETCH_NAMED, not PDO::FETCH_OBJ. Just use the right fetch mode, and you should be fine:
$q->setFetchMode(PDO::FETCH_NAMED);
see the below code, the fetchAll will get the results in an associative array, so you can get the data like $row['serial'] and use it later.
also added the execute() on the pdo statement obj.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->execute(); // make sure to add this
$results = $q->fetchAll();
foreach($results as $row) {
echo htmlspecialchars($row['serial']) . "<br>";
//if you want to use the serial later, just store it into an array
$serials [] = htmlspecialchars($row['serial']);
}
// while ($r = $q->fetch()); this is not needed because of the fetchAll statement above
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
//$r = $q->fetchAll(); not needed here, we did it above already
?>
<?php
//echo htmlspecialchars($r['serial']); use your array from above
print_r($serials);
?>
let me know if it helps

displaying results from mysql with php foreach.... very confused

Hi I'm getting confused as to how to display results with foreach loops. It seems there are slight differences depending on the structure of the array? ie if its a simple array, associative or multi-dimensional? I have looked at other answers for this site but I am still very much confused.
i have connected to mysql db with this code
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '*****',
'*****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
//next i want to retrieve the 'id' and 'name' from a db table...
$results = $pdo->query('select id, name FROM author');
//now I want to display those results on the page... i tried a foreach loop...
foreach ($results as $result) {
echo $result;
}
//but this just displays error message...
Parse error: syntax error, unexpected '$results' (T_VARIABLE), expecting '(' in C:\xampp\htdocs\Connect\admin\authors\test.php on line 6
Please help as im very confused. I just want to know how to display results from a db query like this with a foreach, and what rules apply when displaying different kinds of results from such queries.
I think it involves writing a foreach something like this ....
foreach ($results as $result=> $item) {
echo $item;
}
but i dont undertsand this either.
Any simplified approach to this would be greatly appreciated as I have been stuck on this for some time.
Thanks Rob.
$result is an array not the string.
$stmt = $pdo->prepare("SELECT id, name FROM author");
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['id'];
echo $result['name'];
}
or print the array like this,
foreach ($results as $result) {
print_r($result);
}
You could try it with prepared statements, I always do even if I am not injecting parameters, keeps things a bit clearer.
$stmt = $pdo->prepare('select id, name FROM author');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
You can use the statement fetch method, and with the constant PDO::FETCH_ASSOC to ensure each row is an associative array.
If you're just looking to SELECT something from a database, below is the general format of what you'll need:
try {
//First, you initialise a connection to the database (in this case I'm using *constants*).
$dbh = new PDO('mysql:host=localhost; dbname='.DB_NAME, DB_USER, DB_PASS);
//Secondly, we'll prepare our query - SELECT the id and name FROM table author
$stmt = $dbh->prepare("SELECT id, name FROM author");
// Then we must execute the query
$stmt->execute();
// After execution, we must perform some function to get the results
// This function fetches ALL the results as an array so we can loop
// through them with foreach.
// (Other methods include a while loop and "fetch()" for one row at a time)
$results = $stmt->fetchAll();
// Then we just loop through everything
foreach ($results as $row) {
echo $row['id'];
echo $row['name'];
}
} catch (PDOException $e) {
echo $e->getMessage();
}

Categories