I am trying to adapt my code, which works in a SELECT, to perform an UPDATE. Here, there is no error, but it does not update anything, it even does not even enter the loop. It is supposed to update the room type for the chosen days ($value).
I echoed all values to check them up and they are correct.
$bdd = mysqli_connect('localhost', 'root', '', 'webpage')
$roomty = 1;
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
foreach ($_SESSION['datesBooked_1_month'] as $key => $value)
{
$stmt = mysqli_stmt_init($bdd);
if ( mysqli_stmt_prepare( $stmt , "UPDATE '".$_SESSION['tab_from_month_year']."'
SET '".$_SESSION['roomtype_x']."'='".$_SESSION['roomtype_x']."' + ? WHERE day = ?"))
{
mysqli_stmt_bind_param( $stmt ,'is', $roomty , $value );
mysqli_stmt_execute( $stmt );
mysqli_stmt_close($stmt);
echo " Booked !<br /> ";
}
}
Please try the following code with the new MySql driver of PHP.
you put the quote for a integer value, that is wrong
do you named column with numbers? That is not comfortable.
Are you sure that $value is a string?
Why did you use $key => $value in the foreach loop?
Here the code:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=webpage;host=127.0.0.1';
$user = 'root';
$password = 'dbpass'; #put here yor password
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach $_SESSION['datesBooked_1_month'] as $value) {
#I hope that following variables don't contain space
$query = "UPDATE " .$_SESSION['tab_from_month_year'];
$temp = $_SESSION['roomtype_x'] + $roomty ;
#you wrote that $value is a string, are you sure?
$query .= " SET ".$_SESSION['roomtype_x']. "=$temp WHERE day='$value'" ;
$dbh->query($query);
}
I found out, the problem was the single quotes before the double quotes. It seems to be working very well with only double quotes like this :
if ( mysqli_stmt_prepare( $stmt , "UPDATE ".$_SESSION['tab_from_month_year']." SET ".$_SESSION['roomtype_x']." = ".$_SESSION['roomtype_x']." + ? WHERE day = ?"))
If this is the full code you need to select a database, currently the statement is being sent to the server but not to any database, there for you get no errors. You should use:
mysqli_select_db("You database goes here");
Related
I am trying to do a php code that subtract -1 of quantity stored in a mysql table named ''caffe''.
The table start with 10 and if php is executed with value caffe a quantity in table will be updated.
Will be good some lines of code so i can understand how it work.
read value from url: http://mypage/getdata.php?value=caffe
read value from database table caffe
subtract -1 from the table
update the value of mysql table caffe
<?
$servername = "localhost";
$username = "xxx";
$password = "";
$database = "my_ufficina";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
$txt = $_GET['value'];
if ($txt == caffe)
$count = 1;
echo $count;
I would try something like that :
if ($txt === 'caffe') {
// get Caffe value :
try {
$currentCaffeValue = $conn->query("SELECT yourCaffeValue FROM yourTable");
} catch (Exception $e) {
echo 'db read failed : ', $e->getMessage();
}
// do your stuff then update Caffe value :
try {
$conn->query("UPDATE yourTable SET yourCaffeValue = yourCaffeValue - 1");
} catch (Exception $e) {
echo 'db update failed : ', $e->getMessage();
}
}
And by the way, you should sanitize values from $_GET before using it : http://php.net/manual/en/function.filter-input.php
I have a working SQL query that I'm trying to use in a small PHP script but getting Parse error, tried many variations. Hope you can help. End result would be to have a two field form with 'Date' and 'Channel No' then giving result count of number of 'channel' rows for a given date. Sorry fairly new PHP/SQL, thanks.
<?php
// Connect to MSSQL and select the database
$link = mssql_connect('localhost', 'root', '', 'jm_db');
mssql_select_db('jm_db');
// Select all our records from a table
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
echo $sql;
?>
I have re-done the code but getting 'Warning: mysql_fetch_array() expects parameter 1 to be resource' and undefined variable.
<?php
// Create connection
$mysqli = new mysqli($localhost, $root, $jm_db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
$results= array();
while ($result = mysql_fetch_array($sql)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
?>
You're missing a quote (Stack's syntax highlighting shows you), yet it should be replaced with an opening double quote and ending with the same. You can't use all single quotes.
I replaced the opening single quote with a double, along with a matching closing double quote.
$mysql_query = mssql_query ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
As a sidenote, you're echoing the wrong variable.
However, that is not how you would echo out results, but with a loop.
Something like, and replacing Fieldname with the one you want to use:
while ($row = mssql_fetch_assoc($mysql_query)) {
print $row['Fieldname'] . "\n";
}
or use mssql_fetch_array()
You can also use:
$results= array();
while ($result = mssql_fetch_array($mysql_query)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
For more information on Microsoft SQL Server's function, consult:
http://php.net/manual/en/book.mssql.php
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
while($row=mssql_fetch_array($mysql_query))
{
echo $row[0];
}
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysql_query = mysqli ("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
while ($row = mysql_fetch_array($mysql_query, MYSQL_ASSOC)) {
echo ($row["channel"]);
}
this is a simple example with PDO
<?php
try {
$dns = 'mysql:host=localhost;dbname=jm_db';
$user = 'root';
$pass = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$cnx = new PDO( $dns, $user, $pass, $options );
$select = $cnx->query("SELECT COUNT(*) as count FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
$select->setFetchMode(PDO::FETCH_OBJ);
while( $row = $select->fetch() )
{
echo '<h1>', $row->count , '</h1>';
}
} catch ( Exception $e ) {
echo "Connect failed : ", $e->getMessage();
die();
}
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "  Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}
I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}
Can anyone please tell me how could I fix this code below ? so that I can pull data from host1 (database x , table 1 ) to create table in host2 ( database dx, table2 ),
What am I missing here ? someone tell me to use prepare then fetch array then insert into table2 , can any one show me , how to ?
here's my code
<?php
echo 'Database Connection <br>';
$hostname = "host1";
$hostname1 = "host2";
$username = "myname";
$password = "mypassword";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=x", $username, $password);
echo "Connected to database x<br>"; // check for connection
$dbup = new PDO("mysql:host=$hostname1;dbname=dx", $username, $password);
echo "Connected to database dx<br>"; // check for connection
/*** The SQL SELECT statement ***/
$sql = $dbh->query("select name, choices from table1")or die(print_r($dbh->errorInfo(), true));
$sql1 = $dhup->query("CREATE TABLE api(
`name` VARCHAR(40) NOT NULL,
`choices` VARCHAR(255) NOT NULL )")or die(print_r($dbh->errorInfo(), true));
foreach ($sql as $row)
{
$dbup->exec("insert into table2('name','choices') values('" . $row['name'] . "','" . $row['choices'] . "')") or die(print_r($dbup->errorInfo(), true));
}
// /*** close the database connection ***/
$dbh = null;
$dbup = null;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
Thanks
I noticed you're not consistently spelling "dbup" the same way.
In:
$dbup = new PDO...
You used d'B'up.
In:
$dhup->query("CREATE TABLE...
You used d'H'up.
Maybe this is a simple case of a typographical error?