I got a problem with PDO...
I have this code:
<center>
<?php
/*
$payid = $_GET["payid"];
$data = mysql_connect('localhost','cheapacc_ross2','dsaikoepwq2312','cheapacc_account');
mysql_select_db('cheapacc_account',$data);
$pay1 = mysql_query("SELECT ID,Categorie,Naam,Email,md5_ID FROM acount_Betalingen WHERE md5_ID = '".$payid."' ");
$pay = mysql_fetch_object($pay1);
if($pay){
echo 'betaling is gelukt';
}else{
echo 'Oops jij liegt ons voor?? '.$pay->md5_ID .mysql_error();
}
*/
$flag=0;
require_once '../../include/config.php';
require_once '../../include/processes.php';
$Login_Process = new Login_Process;
$Login_Process->check_status($_SERVER['SCRIPT_NAME']);
$type = base64_decode($_GET["t"]);
$amount = (int)base64_decode($_GET["a"]);
$host = "localhost";
$username = "root";
$password = "20101998";
$dbname = "ross23";
try
{
$db = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $username, $password);
}
catch(PDOException $e)
{
exit("Error database connection. E: " . $e);
}
$info = $_SESSION['info'];
if(!isset($_GET["t"]) || !isset($_GET["a"]) || !isset($_GET["h"]) || sha1(md5($info)) != $_GET["h"])
{
exit("1: FOUT! / You may not change the url, or you get a ip ban!");
}
if(isset($_GET["t"]) && isset($_GET["a"]) && isset($_GET["h"]) && sha1(md5($info)) == $_GET["h"])
{
$q = $db->query("SELECT COUNT(*) FROM account_" . $type . " ");
$count = $q->fetchColumn();
if($count < $amount)
{
die("Er zijn te weinig accounts voor jouw betaling, meld dit aan de administrator!");
}
for($i = 0; $i < $amount; $i++)
{
$flag=0;
$getid = $db->prepare("SELECT id FROM account_".$type." WHERE used = ?");
$getid->execute( array('0') );
$pid = $getid->fetch();
if($pid[0] == null)
{
exit("Er zijn geen accounts over, meld dit aan de administrator!");
}
$id = $pid[0];
$stmt = $db->prepare("SELECT * FROM account_" . $type . " WHERE id = ? AND used = ?");
$stmt->execute( array($id, '0') );
$result = $stmt->fetch();
if(!$result)
{
exit("2: FOUT! / You may not change the url, or you get a ip ban.");
}
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
$userinfo->execute( array($info) );
$userinfo = $userinfo->fetch();
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
$user_id = $_SESSION['userid'] ;
// query
$sql = "INSERT INTO account_lijst (user_id,soort) VALUES (:user_id,:soort)";
$q = $db->prepare($sql);
$q->execute(array(':author'=>$user_id,
':title'=>$type));
$account_info = explode(":", $result[1]);
$html = "Account Username: " . $account_info[0] . "<br />";
$html .= "Account Password : " . $account_info[1];
$html .= "<br /><br />";
$flag = 1;
if ($flag==1){
$sql = $db->prepare("UPDATE account_" . $type . " SET used = ? WHERE ID = ?");
$sql->execute( array("1", $id) );
echo $html;
}
echo 'test';
}
}
The most of the part works but by INSERT INTO account_lijst
It doesn't works...
But i checked everything but i think everything is fine:S...
Can someone help me with this code please?
*EDIT SQL
CREATE TABLE IF NOT EXISTS `account_lijst` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`account` text NOT NULL,
`date` text NOT NULL,
`soort` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
On your query :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
Try that instead :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = :user_id WHERE account = :account");
$sql->bindValue(':user_id', $userinfo['0']);
$sql->bindValue(':account', $result);
$sql->execute();
Should work perfectly if the parameters you gave are the good ones?
If you it doesn't can you please dump the parameters used into the query and the table's structure so we can debug deeper? :)
Check your code i guess (probably) there is an error near of this line due to the way you wrote the where clause:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
Try this instead:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ' ? ' ");
As well in your insert you should use simple apostrophe in ordert o execute that insert:
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
Hope it heps!!
Related
I'm trying to convert this mysql code to work using sqlsrv
$planeId = $_GET["pid"];
$conn = OpenCon();
$sql = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
$stmnt = $conn->prepare($sql);
$stmnt->bind_param("s", $planeId);
$stmnt->bind_result($id, $pid, $fullname, $tat, $date, $engine1, $engine2, $engine3, $engine4);
$stmnt->execute();
$theRows = Array();
while ( $stmnt->fetch() )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
$stmnt->close();
echo json_encode($theRows);
CloseCon($conn);
This I what I've done so far but I'm missing the bind-param function not sure how to implement that. Because the output keeps coming out like this
[{"id":"","pid":"","fullname":null,"tat":null,"date":null,"engine1":null,"engine2":null,"engine3":null,"engine4":null}]
Even though I know there's an entry in Microsoft DB
$planeId = $_GET["pid"];
$theRows = Array();
$conn = OpenCon();
$query = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
//$stmnt = $conn->prepare($query);
$stmnt = sqlsrv_prepare($conn, $query, array(&$planeId));
if (sqlsrv_execute($stmnt) === false){
die( print_r( sqlsrv_errors(), true));
}
else{
while ( sqlsrv_fetch($stmnt) )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
echo json_encode($theRows);
}
CloseCon($conn);
If i don't change at least 1 of the fields values, the update fails.
Insert works ok.
My git
https://github.com/emerson-cs-santos/TSI-PI_2-2019/blob/master/PHP/novo_user.php
If i keep doing this:
$status = $status . ' ';
works, but it's sound me the right solution
-- MYSQL --
CREATE DATABASE IF NOT EXISTS SENAC_PI;
USE SENAC_PI;
CREATE TABLE IF NOT EXISTS USUARIOS
(
codigo INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
,nome VARCHAR(20) NOT NULL
,senha VARCHAR(200) NOT NULL
,tipo VARCHAR(20) NOT NULL
)
;
-- PHP --
<?php
// Open a Connection to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "SENAC_PI";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
echo 'errado';
return;
}
$query = 'use SENAC_PI';
$result = $conn->query($query);
$codigo = 0;
$login = 'teste';
$senha = '123';
$status = 'Ativo';
$query =
" INSERT INTO USUARIOS ( codigo, nome, senha, tipo ) Values (?, ?, ?, ?)";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("isss",$codigo,$login,$senha,$status);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
-- update
$query =
" UPDATE USUARIOS SET nome = ? ,senha = ? , tipo = ? where codigo = ? ";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("sssi",$login,$senha,$status,$codigo);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
}
?>
If i don't change at least 1 of the fields values, then query returns: affected_rows = 0
Thanks to Nigel, i managed to verif the result.
I was using "affected_rows" to valid for errors, but if the user doesn't change something, my code will return as an error.
Using "Rows matched" and "Warnings", i can make sure that my query doesn't have errors.
My final code for the problem:
preg_match_all ('/(\S[^:]+): (\d+)/', $conn->info, $querytratada);
$info = array_combine ($querytratada[1], $querytratada[2]);
// Linhas encontradas com base na condição da where
$linhas_encontradas = $info['Rows matched'];
// Linhas que foram alteradas, quando os dados não forem alterados, mesmo o comando estando certo, não é retornado linhas afetadas
$linhas_afetadas = $info['Changed'];
// Avisos de problemas
$avisos_problemas = $info['Warnings'];
//if ($querytratada->affected_rows > 0)
if ($linhas_encontradas == '1' and $avisos_problemas == '0')
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
Anyway, thanks again Nigel!
I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}
<?php
$db = new mysqli('localhost', 'root', 'root', 'chatting');
$query = "SELECT * FROM user WHERE state = 1 AND getp = 0";
$result = $db->query($query);
$num_result = $result->num_rows;
$mems = "";
for ($i = 0; $i < $num_result; $i++) {
$row = $result->fetch_assoc();
$mems = $row["userName"] . " " . $mems;
$query = "update `user` set `getp` = 1 where 'userName` = ".' $row["userName"] ';
$result = $db->prepare($query);
}
echo $mems;
?>
What I want I want to get all records that state = 1 and getp = 0, then inside loop and for every record I want to change the value of getp to 1, It's correct but don't know where is the wrong.
You forgot to execute() the update statement..
Also, note that this is not the correct way to prepare statements.. you will have to do something like this:
$query = $db->prepare("update `user` set `getp` = 1 where `userName` = :userName");
$query->bind_param(':userName',$row["userName"]);
$result = $query->execute();
Why doing it in a for loop? You could just do UPDATEuserSET getp = 1 WHERE state = 1 AND getp = 0;
While looping with for $i++? Why not while($row = $result->fetch_assoc()) { ... }?
However change the query to
$query = 'update `user` set `getp` = 1 where userName = "'. $row["userName"] .'"';
and don't forget to execute() it.
Please set your update command to:
$query = "update `user` set `getp` = 1 where `userName` = '". $row["userName"]. "'";
include('config.php');
mysqli_select_db($mysqli, "real");
if ($transaction == "Success" && $currency == "USD") {
$user_ids = '".$user_id."'; $total_cred = `user_credits` +'".$package_credits."';
$add = $mysqli->prepare("UPDATE `users` SET `user_credits` = ? WHERE `user_id` = ?");
$add->bind_param('si', $total_cred,$user_ids); $add->execute();
}
The code doesn't throw out any error nor its updating the database .
Change the if block to
// $user_ids = '".$user_id."'; REMOVE THE statement
// $total_cred = `user_credits` + '".$package_credits."'; REMOVE THIS too
$add = $mysqli->prepare("UPDATE `users` SET `user_credits` = `user_credits` + ? WHERE `user_id` = ?");
$add->bind_param('ii', $package_credits, $user_id ); $add->execute();
Let MySQL do the hard part.
Try this one:
include('config.php');
mysqli_select_db($mysqli, "real");
if ($transaction == "Success" && $currency == "USD")
{
$user_ids = '".$user_id."';
$total_cred = user_credits +'".$package_credits."';
$add = $mysqli->prepare("UPDATE users SET user_credits = ? WHERE user_id = ?");
$add->bind_param('si', $total_cred,$user_ids);
$add->execute();
}