try {
$qry = $conn->prepare("SELECT * FROM school_periods WHERE account_id = :a_id");
$qry->execute(array(':a_id'=>$_SESSION['user_account']));
$qry->setFetchMode(PDO::FETCH_OBJ);
while($row = $qry->fetch()) {
?>
<tr>
<td width='35%'><input type='checkbox' name='periods' value=''></td>
<td width='35%'><?=$row->period_name; ?></td>
<td width='35%'><?=$row->start; ?> </td>
<td><?=$row->end; ?></td>
</tr>
<?php
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
If the user checks the number of the checkbox, I want to add the checkbox name and value in the database. I tried to achieve this as follows:
<?php
$schoolyear = $_REQUEST['schoolyear'];
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$start = date2mysql($start);
$end = date2mysql($end);
$holiday = $_POST['holiday'];
$status = 1;
$test = 0;
if ($test == 1) {
echo $schoolyear;
echo '<br />';
echo $start;
echo '<br />';
echo $end;
echo '<br />';
echo $status;
echo '<br />';
echo $_SESSION['user_account'];
}
try {
$sqladdyr = "INSERT INTO school_years (account_id,year_name,start,end,status,added,updated) VALUES (:a_id,:name,:start,:end,:status,NOW(),NOW())";
$q = $conn->prepare($sqladdyr);
$q->bindParam(":start", $start, PDO::PARAM_STR);
$q->bindParam(":end", $end, PDO::PARAM_STR);
$q->bindParam(":a_id", $_SESSION['user_account'], PDO::PARAM_STR);
$q->bindParam(":name", $schoolyear, PDO::PARAM_STR);
$q->bindParam(":status", $status, PDO::PARAM_STR);
$q->execute();
$id = $conn->prepare("SELECT MAX('year_id') FROM school_years");
//Set needed id.
$id->execute();
$id->setFetchMode(PDO::FETCH_OBJ);
while ($idval = $id->fetch()) {
$id_val = $idval->year_id;
}
foreach ( $holiday as $key => $value ):
$stmt = $conn->prepare("INSERT INTO holidays(account_id,year_id,holiday_name,start) VALUES(:a_id,:yid,:name,:date)");
$stmt->execute(array(
':a_id' => $_SESSION['user_account'],
'year_id'=>$id_val,
':name'=>$_POST['holiday'][$key],
':date'=>$_POST['holiday'][$value] // assuming this is the same for all rows?
));
endforeach;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Unfortunately, this does not seem to work. How can I solve this issue?
Related
I'm trying to go through the result of a paremeterized query in PHP.
I'm trying this way
//creating a prepared statement
$stmt = $mysqli->stmt_init();
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0;
while($stmt->fetch())
{
if ($i++%2 == 0) $trow = "even"; else $trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$row['pcode']}</td><td>{$row['price']}</td><td>{$row['description']}</td>";
echo " </tr>";
}
if ($i==0) {
echo "<tr class='even'><td colspan='3'><h3>No Results.</h3></td></tr>";
}
But my code is entering the if statement.
How can I go through the result?
The database is MySQL.
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname) or die('Did you setup/reset the DB? <p><b>SQL Error:</b>' . mysql_error($conn) . '<p><b>SQL Statement:</b>' . $query);
function execute_query($the_query){
global $conn;
$result = mysql_query($the_query) or die('<font size=2><b>SQL Error:</b>' . mysql_error($conn) . '<br/><p><b>SQL Statement:</b>' . $the_query . '<br/>Did you run <i>setupreset.php</i> to setup/reset the DB?</font>');
return $result;
}
?>
You need to bind the result to some variables:
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt = $mysqli->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0; $pcode; $price; $description;
$stmt->bind_result($pcode, $price, $description);
while($stmt->fetch()) {
if ($i++%2 == 0)
$trow = "even";
else
$trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$pcode}</td><td>{$price}</td><td>{$description}</td>";
echo " </tr>";
}
When I click on Add to cart hyperlink, cart.php page is not responding (it's not echoing the add variable. Hyperlink looks fine. However, there is something wrong in cart.php. Any response is appreciated. Thanks in advance.
<html>
<head>
</head>
<body>
<table>
<tr>
<td><?php echo $row['ISBN']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['year']; ?></td>
<td><?php echo $row['price']; ?></td>
<td><?php echo $row['publisher']; ?></td>
<td> Add to cart</td>
<td><?php echo $row['ISBN']; ?></td>
</tr>
</table>
</body>
</html>
cart.php page:
<?php
//
session_start();
$page = 'search.php';
$lpage = 'cart.php';
$db = new mysqli('localhost', 'root', '', 'cheapbook') or die('Error connecting to MySQL server.');
mysqli_set_charset($db, 'utf8');
if (isset($_GET['add'])) {
echo $_GET['add'];
$pieces = explode(":", $_GET['add']);
$quantity = mysqli_query('SELECT ISBN, title from book WHERE ISBN=$pieces[0]');
$result = mysqli_query($db, $quantity);
while ($quantity_row = mysqli_fetch_array($result)) {
if ($quantity_row['quantity'] != $_SESSION['cart_' . $_GET['add']]) {
$_SESSION['cart_' . $_GET['add']] += 1;
}
}
if ($pieces[1] == 'SearchByBookTitle') {
header('location:' . $page . 'SearchByBookTitle=' . $pieces[2]);
}
if ($pieces[1] == 'SearchByAuthor') {
header('location:' . $page . 'SearchByAuthor=' . $pieces[2]);
echo $pieces[1];
} else {
header('location:' . $lpage);
}
}
if (isset($_GET['remove'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['cart'])) {
cart();
}
function cart()
{
foreach ($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5) == 'curt_') {
$total = 0;
$id = substr($name, 5, (strlen($name) - 5));
$get = mysql_query("SELECT ISBN, title, price FROM book where id='.$id.'");
$result = mysqli_query($db, $get);
while ($get_row = mysqli_fetch_array($result)) {
$sub = $get_row['price'] * $value;
echo $get_row['title'] . 'X' . $value . '#Dollar' . $get_row['price'] . '=' . $sub . '[-][+][Delete]';
}
$total += $sub;
}
}
if ($total == 0) {
echo "Your cart is empty";
} else {
echo "Paypal button";
}
}
}
?>
This query coded like this of course will not work as expected
$quantity = mysqli_query('SELECT ISBN, title
from book
WHERE ISBN=$pieces[0]');
You need a double quoted string to use variable expansion, it does not work in a single quoted string.
You also need to add single quotes around the text varibale parameter value
$quantity = mysqli_query("SELECT ISBN, title
from book
WHERE ISBN='$pieces[0]'");
In future you would be well advised to add some error checking code after you attempt to execute a query and also use prepared and parameterised queries to avoid SQL Injection
$sql = "SELECT ISBN, title from book WHERE ISBN=?";
$stmt = mysqli_prepare($sql);
if ( ! $stmt ) {
echo mysqli_error();
exit;
}
$stmt->bind_param('s', $pieces[0] );
$stmt->execute();
what is this. can't do this again and again and again.. lol
if (!isset($_GET['hash'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$hash = 'Teen' . ' ' . chr(38) . ' ' . 'Young Adult';
//otherwise we take the value from the URL
} else {
//if (strpos($_GET['hash'], '&') !== false) {
$regex = "~[ ]\K&~";
$hash = preg_replace($regex, chr(38), $_GET['hash']);
//$hash = preg_replace('/&/', chr(38) ,$_GET['hash']);
//$hash = str_replace("&", chr(38), $_GET['hash']);
echo $hash;
//$hash =
//}
}
//// --- etc etc
$DBH = new PDO($hostDb, $user, $password);
$WTH = $DBH -> prepare( "SELECT asin FROM asin WHERE active=1 AND node = :hash LIMIT $startrow, 10" );
$WTH->bindParam(':hash', $hash, PDO::PARAM_STR);
$WTH->setFetchMode(PDO::FETCH_ASSOC);
$WTH -> execute();
foreach($wea as $item)
{
echo '<td>';
echo '' . $item["node"] . '';
echo '</td>';
echo '<td>';
echo $item["c"];
echo '</td>';
echo '</tr>';
}
echo '</td></tr></table>';
echo '</td></tr></table>';
If this is run, the echo says Only Teen??? and not Teen & Young Adult? Help? Obviously mysql will not take &. Any solutions?
Objective: Take a data entry that contains multiple dates in "$column4" and for each date, create a new entry with $column2, $column3, $column4 and a date followed by one comment.
For this example let's say that:
$column1 is an auto-incrementing primary ID
$column2 = '20141122001';
$column3 = 'something';
$column4 = 'else';
$string = '12/29/2014 2:44PM - working with the lender to remove the mortgage late so we are able to refinance the client. - Person 1 12/04/2014 2:27PM - file suspended until rapid rescore comes back removing late payment from credit. - Person 2';
The example below works for two dates, but how about 1-20 dates? Thanks in advance.
<?php
$host = 'localhost';
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
$db_name = 'intergl8_test';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
echo $string . "<br>";
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches))
{
$date = $matches[2];
}
echo $date;
//////////////////////
if (isset($date)) {
$newstring = str_replace($date,"",$string);
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $newstring, $matches))
{
$date2 = $matches[2];
}
}
echo "<br>";
echo $date2;
////////////////
echo "<br>";
$parts = parse_url($string);
$path_parts= explode($date2, $parts[path]);
$user = $path_parts[1];
$user2 = $path_parts[0];
//$user3 = $path_part[2];
echo $date2 . " " . $user . "<br>";
echo $user2 . "<br>";
$newdate = $date2 . " " . $user;
//echo $user3;
?>
<?php
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
try {
$pdo = new PDO('mysql:host=localhost;dbname=intergl8_test', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $newdate
));
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $user2
));
# Affected Rows?
echo $stmt->rowCount() ." row(s) inserted."; // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
UPDATE:
<?php
$host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
preg_match_all('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "<br>";
/* echo "part 1: " . $val[1] . "<br>";
echo "part 2: " . $val[2] . "<br>";
echo "part 3: " . $val[3] . "<br>";
echo "part 4: " . $val[4] . "<br><br>"; */
// start crazy shit
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host=localhost;dbname='..'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $val[0]
));
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// end crazy shit
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
I am not able to figure out why all of my results are repetitions of the first values it returns.
This code returns the same ID and formatted date repeated over and over again; however, I was expecting it to read a value and then transform that value for each entry in the DB. Here is my code:
<?php
include('../includes/conn.inc.php');
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$stmt->bind_result($id, $endDate);
while($row = $stmt->fetch()) {
$dataRow[] = array('id'=>$id,'endDate'=> $endDate);
};
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($endDate));
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
In your foreach you are always using the last values that were set from the last $stmt->fetch()
Try:
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($i['endDate']));
$id = $i['id'];
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();
}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
use get_result();
$dataRow = array()
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) {
$dataRow[$row['id']] = $row['endDate'];
}
and you don't populate your $endDate in the second loop
foreach($dataRow as $i => $endDate){
$newEndDate = date('Y-m-d',strtotime($endDate));
... // rest of your code